flash
flash

Reputation: 1519

regex with or condition to verify two different patterns?

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.

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

Answers (2)

Youcef LAIDANI
Youcef LAIDANI

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

The fourth bird
The fourth bird

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 string

Regex demo | Java demo

Pattern patternSet = Pattern.compile("^tree[0-9][a-z]?$");

Upvotes: 4

Related Questions