![](/img/trans.png)
[英]how to replace all occurences of a word in a string with another word in java?
[英]Removing all standalone occurences of a word from a string with regular expressions in Java
需要有關如何替換子字符串的建議,例如: @sometext ,但不能替換“ @ someothertext @ somemail.com”子字符串。
例如,當我有一個字符串時,例如:
一個帶有@sometext的示例,也帶有一個“ @ someothertext @ somemail.com”
結果,替換上面字符串中的子字符串后,結果應如下所示:
一個示例,也帶有“ @ someothertext @ somemail.com” sometextafter
從字段中獲取字符串后,我正在使用:
String textMod = someText.replaceAll("( |^)[^\"]@[^@]+?( |$)","");
someText = textMod + "@\"" + someone.getEmail() + "\" ";
然后,我將此字符串設置為字段。
您可以通過這種方式對獨立事件進行正則表達式
\b@sometext\b
將\\ b放在@sometext的前面和后面將確保它是一個獨立的單詞,而不是其他單詞(如@ someothertext @ sometext.com)的一部分。 然后,如果發現結果將放入$ match中,現在您可以使用$ match做任何您想做的事
希望這可以幫助
從https://docs.oracle.com/javase/tutorial/essential/regex/bounds.html
模式中的\\ b表示單詞邊界,因此僅匹配*單詞“ web”,而不匹配部分單詞,例如“ webbing”或“ cobweb”
if (preg_match("/\bweb\b/i", "PHP is the web scripting language of choice.")) {
echo "A match was found.";
}
^ PHP示例,但您明白了這一點
如果在標簽之前和之后始終有一個要替換的空間,這可能就足夠了。
/\s(@\w+)\s/g
這應符合您的需求:
str = str.replaceAll("@\w+[^@]", "");
如果“ @sometext”在句子的開頭或結尾處,則僅在“ @sometext”之前和之后添加空格是行不通的。 但是,僅添加用於檢查句子開頭或結尾的模式也不起作用,因為當您在句子開頭匹配“ @sometext”並留有空格“”時,這會使生成的字符串看起來很奇怪。 句子結尾也一樣。
我們需要將正則表達式替換分為兩個動作,並執行兩個單獨的正則表達式替換:
str = str.replaceAll(" @sometext ", " ");
str = str.replaceAll("^@sometext | @sometext$|(?:@sometext ){2,}", "");
^
表示行的開始, $
表示行的結束。
編輯:增加了幾個@sometext彼此接連時的特殊情況處理。
(C#,基於正則表達式)
//match @xxx sequences, but only if i can look back and NOT see a @xxx immediately preceding me, and if I don't end with a @
string input = @"[An example with @hello and also with ""@@hello@somemail.com"" sometext @lastone";
var pattern = @"(?<!@\w+)(?>@\w+)(?!@)";
var matches = Regex.Matches(input, pattern);
myString = myString.replaceAll(" @hello ", " ");
如果@hello
是一個單詞,那么它前后都有空格,對嗎? 因此,您應該查找所有@hello
之前和之后的空格,並將其替換為空格。
如果您不僅需要刪除@hello
以及所有以@
開頭但不包含其他@
單詞,請使用以下命令:
myString = myString.replaceAll(" @[^@]+? ", " ");
[^@]
是@
以外的任何符號。 +?
表示匹配至少一個字符,直到到達第一個空格。
如果要刪除僅包含字母數字字符的單詞,請使用\\\\w
而不是[^@]
編輯:
是的,奧哈爾(Ohaal)是正確的。 要使其在字符串的開頭和結尾匹配,請使用以下模式:
( |^)@[^@]+?( |$)
myString = myString.replaceAll("( |^)@hello( |$)", " ");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.