gpt4 book ai didi

java - 模式匹配器替换全部

转载 作者:行者123 更新时间:2023-12-01 19:03:51 25 4
gpt4 key购买 nike

我只是试图(徒劳地)在循环期间删除单词“at”的所有实例。

Pattern atPattern = Pattern.compile(".*\\bat\\b.*");
String input = "at Pat's attic a fat cat catcher at patted at"

// required output "Pat's attic a fat cat catcher patted"

output = input.replace(atPattern.pattern(), " ");

output= input.replaceAll(".*\\bat\\b.*", " ");

Matcher atMatcher = atPattern.matcher(input);

output = atMatcher.replaceAll(" ");

// Starting to clutch at straws now...

Matcher atMatcher = Pattern.compile(".*\\bat\\b.*").matcher(input);

output = atMatcher.matcher(input).replaceAll(" ");

output = atPattern.matcher(input).replaceAll(" ");

我也尝试了上述的许多其他组合,但我只是无法获得我想要的输出......

请你让我摆脱痛苦..

最佳答案

单个 replaceAll(...) 就足够了,您需要删除此类 at 之后的一些可选空格:

String input = "at Pat's attic a fat cat catcher at patted at";
String expected = "Pat's attic a fat cat catcher patted";

System.out.println(input.replaceAll("\\bat\\b\\s*", "").trim());
System.out.println(expected.trim());

上面将打印:

Pat's attic a fat cat catcher patted
Pat's attic a fat cat catcher patted

关于java - 模式匹配器替换全部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11071925/

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