English 中文(简体)
感叹号的正向前瞻。
原标题:
  • 时间:2008-11-15 21:26:01
  •  标签:

我正在尝试构建一个Java正则表达式来匹配".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.

有人能让这个工作吗,还是这是JDK的错误?

更新:我感觉自己像个白痴,Pattern.compile("\.jar(?=!)")确实可行。我之前使用了Matcher.matches()而不是Matcher.find()。

最佳回答

使用您的正则表达式对我有效(在Linux上使用Sun JDK 1.6.0_02):

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

Translate this into Chinese:

问题回答

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 
";
    }
  }
}

->

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





相关问题
热门标签