Reputation: 301
Can I use Reg Expression for the following use case?
I Need to write a boolean method which takes a String parameter that should satisfy following conditions.
In this, I have wrote the code for the first requirement: [a-zA-Z0-9]{20} - This expression works well for the first case. I don't know how to write a complete reg expression to meet the entire requirement. Please help.
Upvotes: 0
Views: 194
Reputation: 2019
This regular expression takes
^[0-9]{9}[a-zA-Z]{2}([1-9]|[1-2][0-9]|3[0-1]|99)[a-zA-Z]([0-9]{6})$
takes 9 letters at start, Followed by 2 alphabets, Followed by number between 1 to 31 or 99, Followed by an alphabet, followed by 6 digits.
Upvotes: 0
Reputation: 3821
Your first requirement is already implicit in the remaining ones, so I would just skip it. Then, just write the regex code that matches each part one after the other:
[0-9]{9}[a-zA-Z]{2}...
There is one special consideration for the number that might be 1 to 31. While it is possible to match this in one regex, it would be verbose and difficult to understand. Instead, perform basic matching in the regex and extract this part as a capturing group by putting it into parentheses:
([0-9]{2})
If you use Pattern
and Matcher
to apply your regex, and your string matches the pattern, you can then easily get at just thost two characters, use Integer.parseInt()
to convert them to an integer (which is completely safe because you know the two characters are digits), and then check the value normally.
Upvotes: 0
Reputation: 27307
Yes, it is possible to use regexes for this.
Ignore the "20 characters" part and describe a string created by concatenating 9 digits, 2 letters, 2 digits, 1 letter and another digit.
^
\d
conveniently describes the character set [0-9]
, so \d{9}
means "nine digits"\w
class is too broad, so stick to [a-zA-Z]
for a letter.$
For reference, this regex means "the string is nine letters, then 12-15 or 99, then another letter":
^[a-zA-Z]{9}(1[2-5]|99)[a-zA-Z]$
Upvotes: 2
Reputation: 604
Read the String JavaDocs, especially the part about String.matches() as well as the documentation about regular expressions in Java.
Upvotes: 1