tags:

views:

71

answers:

4

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.

A: 

I'm not sure about Java regexes, but it will be something like

/(apple|orange|peach)/

ie, group them, and use | to say 'or'.

pavium
+1  A: 
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.

VonC
No no no no no .This is an apple <-matchThis is an orange <-matchThis is a peach <-matchThis is a banana <-no match.That's what i mean.
Saobi
A: 

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();
abahgat
I'm using pattern in Java. How can i fit this in?
Saobi
Here you are: I updated the answer
abahgat
+5  A: 

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 ) );
    }
tangens