繁体   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