简体   繁体   English

前缀为@的字符串的Java正则表达式

[英]Java regex for string which was prefixed with @

Say I have the following string 说我有以下字符串

"@apple @banna @? example@test.com"

now I want to make it 现在我要做到

"apple banna ? example@test.com"

What should be my regular expression be to remove "@" symbols without effecting email addresses? 我的正则表达式应该是在不影响电子邮件地址的情况下删除“ @”符号?

I think this will work. 我认为这会起作用。

str = str.replaceAll("(?<!\S)@(?=\S+)");

Here's what this does: 这是这样做的:

(?<!\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.

Here are some quick tests: http://fiddle.re/2vmt 以下是一些快速测试: http : //fiddle.re/2vmt

This question has changed significantly since its original posting. 自从最初发布以来,这个问题已经发生了重大变化。 My original answer, although correct for the question as originally posed, is no longer correct. 我的原始答案尽管对最初提出的问题是正确的,但现在不再正确。

This code will do it: 这段代码可以做到:

String noStrayAts = input.replaceAll("(?<=\\s)@", ""); 

Fyi, here is my previous answer: 菲,这是我以前的回答:

Since both input and output are Strings, and the thing being removed does not require a regex, you simply need: 由于输入和输出都是字符串,并且被删除的东西不需要正则表达式,因此您只需要:

String noAts = input.replace("@", "");
String fruit = fruit.replaceAll("@", " ");

one way of doing this is following : 一种这样做的方法如下:

str.replaceAll("@apple", "apple"); 
str.replaceAll("@banna", "banna"); 
str.replaceAll("@?", "?");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM