tags:

views:

569

answers:

2

I'm trying to build a Java regular expression to match ".jar!"

The catch is that I don't want the matcher to consume the exclamation mark. I tried using Pattern.compile("\\.jar(?=!)") but that failed. As did escaping the exclamation mark.

Can anyone get this to work or is this a JDK bug?

UPDATE: I feel like an idiot, Pattern.compile("\\.jar(?=!)") does work. I was using Matcher.matches() instead of Matcher.find().

A: 
Kent Fredric
I just tried that and unfortunately it doesn't work.
Gili
It isn't semantically any different from the pattern in the question.
Avi
You are right. I've update the question.
Gili
+1  A: 

Using your regex works for me (using Sun JDK 1.6.0_02 for Linux):

import java.util.regex.*;

public class Regex {
        private static final String text = ".jar!";

        private static final String regex = "\\.jar(?=!)";

        public static void main(String[] args) {
                Pattern pat = Pattern.compile(regex, Pattern.DOTALL);
                Matcher matcher = pat.matcher(text);
                if (matcher.find()) {
                        System.out.println("Match: " + matcher.group());
                } else {
                        System.out.println("No match.");
                }
        }
}

prints:

Match: .jar

(without the !)

Avi
Thanks Avi, you're right!
Gili
Your problem might have been that you were using Matcher.matches() instead of .find(), which requires that the entire input pattern matches.
Avi