【问题标题】:How to remove new lines and tabs from text?如何从文本中删除新行和制表符?
【发布时间】:2018-03-06 13:24:03
【问题描述】:

我有这样的文字

"this is line 1\n\t\n\t\tthis is line 2\n\n\n\t\tthis is line 3\t\t\tthis is line 4"

我想要做的是从此文本中删除重复的特定字符(“\n”、“\t”)。

预期结果;

"this is line 1\n\tthis is line 2\n\tthis is line 3\tthis is line 4"

我有下面的正则表达式,但它只会删除重复的字符。

String text = text.replaceAll("([\n\t])\\1+", "$1");

是否有任何正则表达式?

编辑: 例如有一个类似

的文本
"\n\t\tHELLOWORLD\t\t\n\n\n\t"

我想得到的是;

"\n\tHELLOWORLD\t\n"

【问题讨论】:

  • 你能显示预期的字符串结果吗?还是第二个代码示例应该是一个?
  • @Pshemo 是的,第二个文本是预期的结果。
  • 你应该把反斜杠加倍"([\\n\\t])\\1+"
  • @anubhava 不,它不起作用。
  • 我想弄清楚你想要完成什么。现在它看起来像X/Y problem。你真正想解决什么问题(为什么需要这个正则表达式/代码)?

标签: java regex


【解决方案1】:

这里是解决方案;

首先使用第一个正则表达式删除所有重复字符。之后替换连续的文本。

for(int i = 0; i < 10; i++){
    text= text.replaceAll("([\n\t])\\1+", "$1");
    text= text.replaceAll("\n\t\n", "\n\t");
}

【讨论】:

    猜你喜欢
    • 2019-12-05
    • 1970-01-01
    • 2011-03-09
    • 2017-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-26
    相关资源
    最近更新 更多