Reputation: 1519
I need to make a regex where I can verify these two patterns. Basically if any of the string is passed from below two patterns, I should be able to verify it.
tree1
or tree2
. So basically a number preceded by string tree
.tree1a
or tree1b
or tree2a
or tree2b
. So tree[number][a-z] for this pattern.I use below regex but it only works with first pattern. How can I make one regex that can handle both the pattern.
Pattern patternSet = Pattern.compile("^tree[0-9]$");
Upvotes: 0
Views: 301
Reputation: 59978
Your regex should look like so tree\d[a-z]?
, so your pattern can be :
Pattern patternSet = Pattern.compile("tree\\d[a-z]?");
If you want more than a digit and more than a letter you can use :
Pattern patternSet = Pattern.compile("tree\\d+[a-z]*");
the last pattern can match tree123
, tree1abc
or tree123abc
Upvotes: 2
Reputation: 163342
You could add an optional [a-z]?
character class
^tree[0-9][a-z]?$
^
Start of string
tree
Match literally[0-9]
Match a digit 0-9[a-z]?
Optionally match a-z$
End of stringPattern patternSet = Pattern.compile("^tree[0-9][a-z]?$");
Upvotes: 4