Question

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().

Was it helpful?

Solution

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 !)

OTHER TIPS

Additionally, you could try boxing it

Pattern.compile("\\.jar(?=[!])")

Java must be broken: Perl

use strict;
use warnings;


my @data = qw( .jar .jar! .jarx .jarx! );


my @patterns = (
  "\\.jar(?=!)",
  "\\.jar(?=\\!)",
  "\\.jar(?=[!])",
);


for my $pat ( @patterns ){
  for my $inp ( @data ) {
    if ( $inp =~ /$pat/ ) {
      print "$inp =~ $pat \n";
    }
  }
}

->

.jar! =~ \.jar(?=!) 
.jar! =~ \.jar(?=\!) 
.jar! =~ \.jar(?=[!]) 

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top