gpt4 book ai didi

java - 给定字符串前后包含任何字符的正则表达式

转载 作者:行者123 更新时间:2023-12-01 18:05:41 25 4
gpt4 key购买 nike

我收到以下文本:Unbekannter Fehler:尝试调用从局部变量“libInfo”加载的空对象的方法 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,但为什么呢?我只想检查文本是否包含在另一个带有正则表达式的文本中(否 String.contains(...))。如果我正确阅读它,我必须在正则表达式的开头和结尾使用 .* 来确保它不会介意要检查的字符串前面或后面的内容。

最佳答案

首先确保所有字符都已正确转义。尝试使用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!");
}

关于java - 给定字符串前后包含任何字符的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36624440/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com