简体   繁体   中英

Regex with any character in front and after given string

I've got the following text: 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!");
}

If I run the above code, it returns false , but why? I just want to check, if the text is contained by the other one with regular expression (No String.contains(...) ). If I read it properly, I have to use .* at the beginning and at the end of the regex to be sure, that it neverminds, what is coming in front or after the string to check.

Make sure all of your characters are properly escaped first. Try using 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!");
}

You have to quote the parentheses in the pattern.

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

You shouldn't need the .* at the beginning, nor the end though.

Regards

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM