Sahar Hassan
Sahar Hassan

Reputation: 301

Reg Expression Validation on a String

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

Answers (4)

Abhishek
Abhishek

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

Medo42
Medo42

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

John Dvorak
John Dvorak

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.

  • Start with the string start: ^
  • Then 9 digits. The \d conveniently describes the character set [0-9], so \d{9} means "nine digits"
  • Then 2 letters. The \w class is too broad, so stick to [a-zA-Z] for a letter.
  • Then another two digits. They seem to be from a restricted set, so describe the set with alternation and grouping.
  • Then another letter and another digit.
  • And, finally, you have to end at the end of the string: $

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

Uli
Uli

Reputation: 604

Read the String JavaDocs, especially the part about String.matches() as well as the documentation about regular expressions in Java.

Upvotes: 1

Related Questions