Reputation: 17021
How do I match a list of words using regular expression.
Like I want to match
This is a apple
This is a orange
This is a peach
I tried This is a [apple|range|peach]
.
Does not work.
Any ideas? I've sent 5 hours on this, there are "rules" published, but without exhaustive examples, these rules are too mystic.
Upvotes: 2
Views: 1763
Reputation: 13530
Try this:
String str = "This is a peach";
boolean matches = str.matches("(apple|orange|peach)");
If you use a pattern, then 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();
Upvotes: 0
Reputation: 1323953
This is a ((?:(?:apple|orange|peach)/?)+)
will match
This is a apple/orange/peach.
whatever the order is .
You will get only one capturing group representing the all list.
(here "apple/orange/peach").
(?:apple|orange|peach)
' means: match one of those three terms, do not capture it(?:.../?)+
': match a string finished by '/' or not, multiple times(...)
': capture the all list.This is an apple <-match This is an orange <-match This is a peach <-match This is a banana <-no match.
This is a (apple|orange|peach)
is enough: [apple|orange|peach]
that you tried is actually a character class, and would match any 'a', 'p', '|', 'o', ... etc.
Upvotes: 1
Reputation: 39733
You can use
Pattern pattern = Pattern.compile( "This is a (apple|orange|peach)" );
Matcher matcher = pattern.matcher( "This is a orange" );
if( matcher.find() ) {
System.out.println( matcher.group( 1 ) );
}
Upvotes: 5
Reputation: 15118
I'm not sure about Java regexes, but it will be something like
/(apple|orange|peach)/
ie, group them, and use | to say 'or'.
Upvotes: 0