正则表达式:如何删除每行冒号前的所有内容

Regex: How to remove everything before a colon on each line

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

^[^:]+:\s*

以下需要改自

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

Afghanistan
Albania
Algeria
Andorra
Angola

有什么指点吗?

如果要保证不跨行溢出,需要在取反字符class后面加上\r\n,把可以匹配换行符的\s换成\h(水平空白模式)(如果不支持 \h,则为 [ \t])。

所以,您可以使用

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

(see demo) 或

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

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

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

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

替换为</code>。参见 <a href="https://regex101.com/r/uB6tGc/3" rel="nofollow noreferrer">yet another regex demo</a>。</p> <p><strong>图案详情</strong></p> <ul> <li><code>^ - 行首(如果不是默认的,在前面加上 (?m) 内联修饰符)

  • [^:\r\n]+ - 除了 :、CR 和 LF
  • 之外的 1 个或更多字符
  • : - 冒号
  • \h* - 零个或多个水平空格
  • (.*) - 第 1 组(从替换模式中引用 </code> 或 <code>)捕获除换行符以外的任何零个或多个字符,尽可能多(到行尾)。
  • echo "afghanistan : Afghanistan" | sed 's/\(.*\):\(.*\)//'