【问题标题】:Regex: How to remove everything before a colon on each line正则表达式:如何删除每行冒号前的所有内容
【发布时间】:2017-07-31 20:03:35
【问题描述】:

我尝试使用此正则表达式删除冒号前的所有内容,但是,它会递归删除。

^[^:]+:\s*

以下需要改自

afghanistan : Afghanistan
albania : Albania
algeria : Algeria
andorra : Andorra
angola : Angola

Afghanistan
Albania
Algeria
Andorra
Angola

任何指针?

【问题讨论】:

标签: regex regex-lookarounds regex-greedy


【解决方案1】:

如果要确保不会跨行溢出,则需要将\r\n 添加到否定字符类中,并将可以匹配换行符的\s 替换为\h(水平空格模式)(或@ 987654327@ 如果不支持\h)。

所以,你可以使用

^[^:\r\n]+:\h*

(see demo) 或

^[^:\r\n]+:[ \t]*

替换为空字符串 (another demo)。

在 Notepad++ 中,你需要匹配整行来摆脱递归行为:

^[^:\r\n]+:\h*(.*)

替换为\1。见yet another regex demo

模式详情

  • ^ - 行首(如果不是默认值,在前面加上 (?m) 内联修饰符)
  • [^:\r\n]+ - 除:、CR 和 LF 之外的 1 个或多个字符
  • : - 冒号
  • \h* - 零个或多个水平空格
  • (.*) - 第 1 组(指替换模式中的 \1$1)尽可能多地捕获除换行符之外的任何零个或多个字符(直到行尾)。

【讨论】:

    【解决方案2】:
    echo "afghanistan : Afghanistan" | sed 's/\(.*\):\(.*\)/\2/'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-27
      • 1970-01-01
      • 2010-10-16
      相关资源
      最近更新 更多