itun
itun

Reputation: 3521

Pattern lookahead

Pattern p = Pattern.compile("(ma)|([a-zA-Z_]+)");
Matcher m = p.matcher("ma");
m.find();
System.out.println("1 " + m.group(1) + ""); //ma
System.out.println("2 " + m.group(2)); // null
Matcher m = p.matcher("mad");
m.find();
System.out.println("1 " + m.group(1) + ""); //ma
System.out.println("2 " + m.group(2)); // null

But I need that the string "mad" would be in the 2nd group.

Upvotes: 2

Views: 1344

Answers (2)

Mike Sokolov
Mike Sokolov

Reputation: 7044

I think what you are looking for is something like:

(ma(?!d))|([a-zA-Z_]+)

from "perldoc perlre":

"(?!pattern)" A zero-width negative look-ahead assertion. For example "/foo(?!bar)/" matches any occurrence of "foo" that isn't followed by "bar".

the only thing I'm not sure about is whether Java supports this syntax, but I think it does.

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1499880

If you use matches instead of find, it will try to match the entire string against that pattern, which it can only do by putting mad in the second group:

import java.util.regex.*;

public class Test {
    public static void main(String[] args) {
        Pattern p = Pattern.compile("(ma)|([a-zA-Z_]+)");
        Matcher m = p.matcher("ma"); 
        m.matches();
        System.out.println("1 " + m.group(1)); // ma
        System.out.println("2 " + m.group(2)); // null
        m = p.matcher("mad"); 
        m.matches();
        System.out.println("1 " + m.group(1)); // null
        System.out.println("2 " + m.group(2)); // mad
    }
}

Upvotes: 0

Related Questions