-1

I'm trying to develop some problems that my instructor gave me, and one of those problems is asking me to check if the input string complies with the following rules:

  1. That the string contains numbers from 2 to 9.
  2. That the string contains the letters TJQKA.
  3. If within the string there is any other letter outside the mentioned ones, then the String is invalid.

EX:

643TJAKQ = Ok

72MAJTQ = Not Okay

1246AKJQ = Not Okay

AKT432 = Ok

This obviously is a Regex problem, because if I try to filter by lists, arrays or something else, It's going to take too much time just validating this (And I writting the code). I tried with this reg exp (/[2-9]|(T|J|Q|K|A)/g) but is garbage.

TwoDent
  • 351
  • 3
  • 22
  • `\b[2-9TJQKA]+\b` – depperm Jul 11 '19 at 17:22
  • "*I tried with this reg exp (/[2-9]|(T|J|Q|K|A)/g) but is garbage*" What? Why is it garbage? What do you mean by this? Please elaborate. – esqew Jul 11 '19 at 17:23
  • @esqew It's too obvious, is not working. When I use this exp with the function "matches" in java, is always trowing false. – TwoDent Jul 11 '19 at 17:27
  • That said, check out this question: [Reference - What does this regex mean?](https://stackoverflow.com/questions/22937618/reference-what-does-this-regex-mean). Its "answer" has links to many other helpful pages. – Slaw Jul 11 '19 at 18:53

4 Answers4

3

the following regex works: ^[2-9TJQKA]+$

explanation:

^: start

[2-9TJQKA]: define allowed values

+: allow more than one character Strings

$: end

nLee
  • 1,230
  • 2
  • 10
  • 20
  • Thank you very very very much for your explanations. I'm going to create a few custom ones to pratice and try. – TwoDent Jul 11 '19 at 17:46
2

You can simply define the allowed characters:

[2-9TJQKA]+

Michael
  • 824
  • 3
  • 8
1
Boolean okayOrNot = someString.matches("[2-9TJQKA]+");
Chrisvin Jem
  • 3,456
  • 1
  • 5
  • 23
-1

I would recommend the regex: \b[2-9TJQKA]+\b

2-9-accept only numbers between 2 and 9

TJQKA-accept only these characters

\b-only words with only these characters

regex101 also on free formatter

depperm
  • 8,490
  • 4
  • 37
  • 57