说我有以下字符串
"@apple @banna @? example@test.com"
现在我想成功
"apple banna ? example@test.com"
我的正则表达式应该是什么来删除“@”符号而不影响电子邮件地址?
我认为这会奏效。
str = str.replaceAll("(?<!\S)@(?=\S+)");
这是这样做的:
(?<!\S) // Checks to make sure that the @ is preceded by a whitespace
// character, or is the beginning of the string. This exists to make sure we're not in an email.
@ // Literal @
(?=\S+) // Makes sure that something besides whitespace follows.
以下是一些快速测试: http: //fiddle.re/2vmt
自最初发布以来,此问题已发生重大变化。我最初的答案虽然对最初提出的问题是正确的,但不再正确。
此代码将执行此操作:
String noStrayAts = input.replaceAll("(?<=\\s)@", "");
仅供参考,这是我之前的回答:
由于输入和输出都是字符串,并且被删除的东西不需要正则表达式,您只需要:
String noAts = input.replace("@", "");
String fruit = fruit.replaceAll("@", " ");
一种方法如下:
str.replaceAll("@apple", "apple");
str.replaceAll("@banna", "banna");
str.replaceAll("@?", "?");