Reputation: 1257
I am using java regex library to find a pattern "String_OneOrMoreDigits". For example, "linenumber_1" or "linenumber_31" or "linenumber_456". I am trying the following pattern assuming I will get string of type "linenumber_2" or "linenumber_44". However, I just get the strings of type "linenumber_2", it does not match more than one number at the end. How to go about matching such strings?
Pattern pattern = Pattern.compile("(linenumber_[0-9])|(linenumber_[0-9][0-9])");
Upvotes: 2
Views: 753
Reputation: 11233
you can also use:
Pattern pattern = Pattern.compile("linenumber_\d+");
and if you need a case insensitive match, append (?i)
at the start like this:
Pattern pattern = Pattern.compile("(?i)linenumber_\d+");
(?i)
allows regex engine to perform case insensitive match.
\d
would match any digit from 0 to 9
Upvotes: 1
Reputation: 4908
to add on if you want specific amount of digits, instead of
Pattern pattern = Pattern.compile("linenumber_[0-9]{1,2}");
you could also use
Pattern pattern = Pattern.compile("linenumber_[0-9]{1|4|8}");
which would specify that you want either 1 digit, 4 digits or 8 digits. and like Crowder said,
Pattern pattern = Pattern.compile("linenumber_[0-9]+");
would match with any number of digits.
Upvotes: 2
Reputation: 1073968
No need for an alternation, just use a "one or more" qualifier on the [0-9]
:
Pattern pattern = Pattern.compile("linenumber_[0-9]+");
That will match "linenumber_1" and "linenumber_44" and "linenumber_12345984". If you only want to match one or two digits, you can do that by being more explicit about the number of digits allowed:
Pattern pattern = Pattern.compile("linenumber_[0-9]{1,2}");
Upvotes: 6