如何删除 java 中包含特定字符的单词?

How do I delete words containing a certain charater in java?

有没有办法使用正则表达式删除包含“@”字符的整个单词?

例如,应删除以下单词:kʌn@tənɪub@ilu

我试过:

line = br.readLine();
line = line.replaceAll("\b[@]+\b","");
System.out.println(line);

...只删除“@”符号,不删除单词本身。

line = br.readLine();
line = line.replaceAll("\b.+?[@]+.+?\b","");
System.out.println(line);

编辑:.*? 不好。我测试了最新的编辑,它对我有用。

    String test =  "  x+1@ three@two @@ o@ne @ two";
    test = test.replaceAll("\b.+?[@]+.+?\b","");
    System.out.println(test);

给予

two

使用正则表达式

[^@\s]*@\S*

[^@\s]* 查找零个或多个不是“@”或空格的字符

@ 寻找一个 '@'

\s* 查找零个或多个非空白字符

所以代码行是:

line = line.replaceAll("[^@\s]*@\s*","");

您可以使用如下正则表达式:

(\s+)([^\s]*?@[^\s]*?)(\s+)

如果您想用它周围的两个空格替换它,您可以将其替换为 </code>。</p> <p>如果你只想用一个空格替换它(这样看起来更好),你可以用 <code></code>.</p> 替换它 <p><a href="https://regex101.com/r/dI8qN3/2" rel="nofollow noreferrer">Here's a preview of the regex in action</a> 在 regex101.com 上,它是这样工作的:</p> <blockquote> <p><code>\s matches any whitespace character
\s+ maches any whitespace character one or more times.

[^\s] matches any non-whitespace character
[^\s]*? matches any non-whitespace character any amount of times, and tries to find the smallest match.

@ matches the character @ literally.

[^\s] matches any non-whitespace character
[^\s]*? matches any non-whitespace character any amount of times, and tries to find the smallest match.

\s matches any whitespace character
\s+ maches any whitespace character one or more times.