簡體   English   中英

如何從字符串中刪除特定的特殊字符模式

[英]How to remove a specific special character pattern from a string

我有一個字符串名稱s,

String s = "<NOUN>Sam</NOUN> , a student of the University of oxford , won the Ethugalpura International Rating Chess Tournament which concluded on Dec.22 at the Blue Olympiad Hotel";  

我想從字符串中刪除所有< NOUN >和< / NOUN >標記。 我用它來刪除標簽,

s.replaceAll("[<NOUN>,</NOUN>]","");

是的,它刪除了標簽。 但它也會從字符串中刪除字母“U”和“O”字符,這會給我以下輸出。

 Sam , a student of the niversity of oxford , won the Ethugalpura International Rating Chess Tournament which concluded on Dec.22 at the Blue lympiad Hotel

誰能告訴我如何正確地做到這一點?

嘗試:

s.replaceAll("<NOUN>|</NOUN>", "");

在RegEx中,語法[...]將匹配括號內的每個字符 ,無論它們出現的順序如何。因此,在您的示例中,所有外觀“<”,“N”,“O”等都將被刪除。 而是使用管道( | )來匹配“<NOUN>”和“</ NOUN>”。

以下也應該有效(並且可以被認為更干燥和優雅)因為它將匹配帶有和不帶正斜杠的標簽:

s.replaceAll("</?NOUN>", "");

String.replaceAll()將正則表達式作為其第一個參數。 正則表達式:

"[<NOUN>,</NOUN>]"

在括號內定義要識別並因此刪除的字符集 因此,您要求刪除字符<>/NOU和逗號。

也許最簡單的方法就是做你想要的:

s.replaceAll("<NOUN>","").replaceAll("</NOUN>","");

這是明確的刪除。 更復雜的正則表達式顯然是可能的。

你可以使用一個正則表達式:“<[/] * NOUN>”所以

s.replaceAll("<[/]*NOUN>","");

應該做的伎倆。 “[/] *”在“<”之后匹配零或更多“/”。

試試這個: String result = originValue.replaceAll("\\\\<.*?>", "");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM