Java 给定字符串前后任意字符的正则表达式

Java 给定字符串前后任意字符的正则表达式,java,regex,pattern-matching,Java,Regex,Pattern Matching,我得到了以下文本:unbekannert-Fehler:试图调用从局部变量'libInfo'加载的null对象的test()方法时。 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 l

我得到了以下文本:
unbekannert-Fehler:试图调用从局部变量'libInfo'加载的null对象的test()方法时。

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(…)
)。如果我读得正确,我必须在正则表达式的开头和结尾使用
*
,以确保它不需要检查字符串前面或后面的内容。

您必须在模式中引用括号

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);
您不应该在开始时使用
*
,也不应该在结束时使用


关于

您必须在模式中引用括号

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);
您不应该在开始时使用
*
,也不应该在结束时使用


请确保首先正确转义所有字符。尝试使用
模式#引号

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

首先确保所有字符都已正确转义。尝试使用
模式#引号

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

继续从模式中删除字符,直到匹配为止,您将知道哪些字符导致不匹配。继续从模式中删除字符,直到匹配为止,您将知道哪些字符导致不匹配。