【问题标题】:How to replace multiple whitespaces without modifying newline characters?如何在不修改换行符的情况下替换多个空格?
【发布时间】:2014-11-16 11:52:56
【问题描述】:

所以正如标题所说,我在用单个空格符号替换多个空格和 \t 时遇到了很大的问题。例如,我有以下字符串:

   &!(0-=\+_)(         ^(there goes '\n')
   &!(0-=\+_)(     

如您所见,我的字符串由 \t 和 \s 符号组成。这个方法我已经试过了:

line = Regex.Replace(line, @"\t+", " ");
line = Regex.Replace(line, @"\s+", " ");

但最后我收到了简单的字符串,没有换行符。那么......如果有任何方法可以忽略换行符?提前致谢!

【问题讨论】:

    标签: c# regex


    【解决方案1】:

    试试这个:

    line = Regex.Replace(line, @"\t+", " ");
    line = Regex.Replace(line, @" +", " ");
    

    它将字符串"a b c\t\t\t\nd e f" 转换为a b c \nd e f


    有关解释,请参见例如:http://www.ntu.edu.sg/home/ehchua/programming/howto/Regexe.html

    The \s (lowercase s) matches a whitespace (blank, tab \t, form-feed \f and newline \r or \n).

    【讨论】:

    • 谢谢,它有效!你能解释一下为什么用 "\s+" 是不可能的吗?
    【解决方案2】:
    [ ]+
    

    试试这个。它对我有用。参见演示。替换为space

    http://regex101.com/r/lZ5mN8/12

    \s=[\r\n\t\f ]

    它包含newline.所以它不会工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-04
      • 1970-01-01
      • 1970-01-01
      • 2022-06-16
      相关资源
      最近更新 更多