【问题标题】:Regex remove additional spaces and line breaks but not all [duplicate]正则表达式删除额外的空格和换行符,但不是全部[重复]
【发布时间】:2018-09-23 03:49:13
【问题描述】:

我正在使用正则表达式来删除额外的空格。但我想保留单个换行符。

'/\s+/'

如何保留单行换行符?

只删除多余的不必要的空格和换行符。

我已经尝试过'/\s{2,}/',但这仍然会删除我的换行符。

【问题讨论】:

  • 你能提供测试用例和你正在使用的语言吗?
  • 使用'/\h{2,}/'。或者,'/[^\S\n]{2,}/',或'/[^\S\n\r]{2,}/'

标签: regex


【解决方案1】:

这将匹配额外的空格和新行:

(?<= ) | +$|(?<=\n)\n

解释(空格文字替换为“[space]”):

(?<=[space])[space] | Match any space that has a preceding space
|                   | or
[space]+$           | Match one or more consecutive spaces at the end of a line
|                   | or
(?<=\n)\n           | Match any new line that has a preceding new line

全局和多行标志应与此表达式一起使用。只需将匹配项替换为空即可。

Try it here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-10
    • 2019-06-21
    • 1970-01-01
    • 2016-06-17
    • 1970-01-01
    • 1970-01-01
    • 2021-11-29
    相关资源
    最近更新 更多