Regular expression to match a single variable word sentence
How to match a word list using regular expression.
How I want to match
This is a apple
This is a orange
This is a peach
I tried it This is a [apple|range|peach]
.
Does not work.
Any ideas? I sent 5 hours to this, the "rules" are published, but without exhaustive examples, these rules are too mystical.
+2
source to share
4 answers
This is a ((?:(?:apple|orange|peach)/?)+)
will match
This is a apple/orange/peach.
regardless of order.
You will only get one capture group representing the entire list.
(here "apple / orange / peach").
- '
(?:apple|orange|peach)
' means: matching one of these three terms, do not write it down - '
(?:.../?)+
': match string terminated with '/' or multiple times - '
(...)
': grab the entire list.
This is an apple <-match. It's orange <-match. This is a peach <-match. This is a banana match.
This is a (apple|orange|peach)
enough: the [apple|orange|peach]
one you've tried is actually a character class and will match any 'a', 'p' '|', 'o', ... etc.
+1
source to share
Try the following:
String str = "This is a peach";
boolean matches = str.matches("(apple|orange|peach)");
If you are using a template you can use
String str = "This is a peach";
Pattern pat = Pattern.compile("(apple|orange|peach)");
Matcher matcher = pat.matcher(str);
boolean matches = matcher.find();
0
source to share