在给定字符串前面和后面的任何字符的正则表达式

时间:2016-04-14 13:21:12

标签: java regex pattern-matching

我有以下文字:Unbekannter Fehler: while trying to invoke the method test() of a null object loaded from local variable 'libInfo'

Matcher matcher = null;
Pattern pattern = null;
try
{
    pattern = Pattern.compile(".*" + "Unbekannter Fehler: while trying to invoke the method test() of a null object loaded from local variable 'libInfo'" + ".*", Pattern.CASE_INSENSITIVE & Pattern.DOTALL);
    matcher = pattern.matcher("Unbekannter Fehler: while trying to invoke the method test() of a null object loaded from local variable 'libInfo'");

    if (matcher.matches())
        System.out.println("Same!");
}

如果我运行上面的代码,它会返回false,但为什么呢?我只是想检查一下,如果文本是由另一个包含正则表达式的文本(No String.contains(...))。如果我正确地阅读它,我必须在正则表达式的开头和结尾处使用.*以确保它永远不会发生,前面或后面要检查的内容是什么。

2 个答案:

答案 0 :(得分:3)

确保首先正确转义所有字符。尝试使用Pattern#quote

String test = "Unbekannter Fehler: while trying to invoke the method test() of a null object loaded from local variable 'libInfo'";

Pattern pattern = Pattern.compile(".*" + Pattern.quote(test)  + ".*", Pattern.CASE_INSENSITIVE & Pattern.DOTALL);
Matcher matcher = pattern.matcher(test);

if (matcher.matches()) {
    System.out.println("Same!");
}

答案 1 :(得分:1)

你必须在模式中引用括号。

pattern = Pattern.compile("Unbekannter Fehler: while trying to invoke the method test\\(\\) of a null object loaded from local variable 'libInfo'", Pattern.CASE_INSENSITIVE & Pattern.DOTALL);

你不应该在开始时需要.*,也不应该在结束时使用{。}}。

此致