【问题标题】:Why doesn't sed respect the simple regex? [duplicate]为什么 sed 不尊重简单的正则表达式? [复制]
【发布时间】:2019-12-22 10:56:00
【问题描述】:
  • 我的短信:mmhmmh here_is_you 05451ab8 888
  • 我的正则表达式:mmhmmh \w* ([ab0-9]*) \d*
  • 我的 sed 命令:echo "mmhmmh here_is_you 05451ab8 888" | sed -n 's/mmhmmh \w* \([ab0-9]*\) \d*/\1/p'
  • 结果:05451ab8888 而不是 05451ab8

为什么 sed 不尊重我的正则表达式?我检查了一下,我的正则表达式应该正确地选择了预期的结果。

【问题讨论】:

标签: sed


【解决方案1】:

正如 Cyrus 在评论链接中指出的那样,\d 确实存在问题,请使用 [0-9]

echo "mmhmmh here_is_you 05451ab8 888" | sed -n 's/mmhmmh [a-zA-Z0-9_]* \([ab0-9]*\) [0-9]*/\1/p'
05451ab8

[[:digit:]]

echo "mmhmmh here_is_you 05451ab8 888" | sed -n 's/mmhmmh [[:alnum:]_]* \([ab0-9]*\) [[:digit:]]*/\1/p'
05451ab8

正如 trpleee 指出的那样,也不要使用\w

【讨论】:

  • 您还需要修复\w。它可能适用于某些sed 变体,但它不可移植。
  • @triplee 已更新。
猜你喜欢
  • 1970-01-01
  • 2013-01-18
  • 2020-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-12
相关资源
最近更新 更多