0

我只是尝试(徒劳地)在循环期间删除单词“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(" "); 

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

请你能让我摆脱我的痛苦..

4

3 回答 3

2

A single replaceAll(...) is sufficient, and you'll need to remove some optional spaces after such at's:

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

The above will print:

Pat's attic a fat cat catcher patted
Pat's attic a fat cat catcher patted
于 2012-06-17T14:19:03.967 回答
1

可以简单地通过以下方式完成:

"at Pat's attic a fat cat catcher at patted at"
    .replaceAll("\\bat\\b","").trim().replaceAll(" +", " ")

trim()和第二个用于replaceAll()删除空格。

可能还有其他方法可以一步完成所有这些(可能更快?),但是将它们分开更容易考虑逻辑。

编辑

以防万一,这是一个一步解决方案:

.replaceAll("(?i)(\\bat\\b | ?\\bat\\b)","")

添加 是为了(?i)不区分大小写。如果不需要,您可以将其删除。

于 2012-06-17T14:17:12.113 回答
1

You could do this

.replaceAll("(\\s|^)(at)(\\s|$)", " ").trim()
于 2012-06-17T14:24:49.147 回答