gpt4 book ai didi

java分组正则表达式无法匹配字符串+文本

转载 作者:行者123 更新时间:2023-12-02 03:23:31 27 4
gpt4 key购买 nike

我写了这个测试

@Test
public void removeRequestTextFromRouteError() throws Exception {
String input = "Failed to handle request regression_4828 HISTORIC_TIME from=s:33901510 tn:27825741 bd:false st:Winifred~Dr to=s:-1 d:false f:-1.0 x:-73.92752 y:40.696857 r:-1.0 cd:-1.0 fn:-1 tn:-1 bd:true 1 null false null on subject RoutingRequest";
final String answer = stringUtils.removeRequestTextFromError(input);
String expected = "Failed to handle request _ on subject RoutingRequest";
assertThat(answer, equalTo(expected));
}

运行此方法,但失败

public String removeRequestTextFromError(String answer) {
answer = answer.replaceAll("regression_\\d\\[.*?\\] on subject", "_ on subject");
return answer;

}

输入文本保持不变,不替换为“_”

如何更改模式匹配来解决此问题?

最佳答案

您使用了错误的正则表达式。您正在转义 [] (根本没有必要)并使用 \\d 而不是 \\d+ 。另外,您应该使用积极的前瞻,而不是实际选择和替换字符串“on subject”

用途:

public static void main(String[] args) {
String input = "Failed to handle request regression_4828 HISTORIC_TIME from=s:33901510 tn:27825741 bd:false st:Winifred~Dr to=s:-1 d:false f:-1.0 x:-73.92752 y:40.696857 r:-1.0 cd:-1.0 fn:-1 tn:-1 bd:true 1 null false null on subject RoutingRequest";
final String answer = input.replaceAll("regression_.* (?=on subject)", "_ ");
System.out.println(answer);
String expected = "Failed to handle request _ on subject RoutingRequest";
System.out.println(answer.equals(expected));
}

操作:

Failed to handle request _ on subject RoutingRequest
true

关于java分组正则表达式无法匹配字符串+文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39314623/

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