簡體   English   中英

如何從文本中刪除特定的重復字符?

[英]How to remove specific repeated characters from text?

我有一個像

"this is line 1\n\n\nthis is line 2\n\n\nthis is line 3\t\t\tthis is line 3 also"

我想做的是從此文本中刪除重復的特定字符,例如“ \\ n”,“ \\ t”。

"this is line 1\nthis is line 2\nthis is line 3\tthis is line 3 also"

我嘗試了一些正則表達式,但對我沒有用。

text = text.replace("/[^\\w\\s]|(.)\\1/gi", ""); 

是否有此用的正則表達式?

如果只需要刪除分隔的空白字符,則\\s將無濟於事,因為它會過度匹配,即也將匹配空格,硬空格等。

您可以將字符類與char一起使用,將它們與捕獲組包裝在一起,並對捕獲的值使用反向引用。 並替換為對組1值的反向引用:

.replaceAll("([\n\t])\\1+", "$1")

參見regex演示

細節

  • ([\\n\\t]) -組1(模式中用\\1 ,替換模式中用$1 ):匹配換行符或制表符的字符類
  • \\1+ -組1中值的一個或多個重復。

我會用番石榴的CharMatcher

CharMatcher.javaIsoControl().removeFrom(myString)

暫無
暫無

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

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