BlueGirl
BlueGirl

Reputation: 501

Regular expression does not match

I need to define a pattern for a string and find all matches of that in a sentence in java eclipse environment. This in my code:

public static final String EXAMPLE_TEST = "MD_pos ";
public static final String REGEX ="(RB_pos)?(MD_pos|VB_pos|VBD_pos|VBP_pos|VBZ_pos|VBG_pos|VBN_pos) (RP_pos)? (RB_pos)? ";

public void PatMat() {

    Pattern pattern = Pattern.compile(REGEX);
    Matcher matcher = pattern.matcher(EXAMPLE_TEST);

    int count = 0;
    while(matcher.find()) {
        count++;
        System.out.println("found: " + count + " : "
            + matcher.start() + " - " + matcher.end());
        System.out.println("found: " + matcher.group());  
    }
}

Parts with ? sign in pattern are optional so MD_pos should be matched. But everytime I call this method there is no result in console.

Upvotes: 0

Views: 71

Answers (2)

Unihedron
Unihedron

Reputation: 11041

You forgot to compile in COMMENTS mode so the spaces are ignored.

Pattern pattern = Pattern.compile(REGEX, Pattern.COMMENTS);

Upvotes: 1

Joe
Joe

Reputation: 31057

Your REGEX contains three non-optional spaces, which aren't present in the sample string you're trying to match.

Upvotes: 5

Related Questions