“贪婪”搜索并替换 sed

问题描述 投票:0回答:1

我有一个 bash 函数,可以从字符串中获取前缀,直到并包括字符“-”。

get_prefix_with_hyphen() {
  # get prefix with trailing hyphen
  prefix_with_hyphen=$(echo "$1" | sed 's/-.*$/-/')
  if [ "$prefix_with_hyphen" = "$1" ]; then
    echo ""
  else
    echo "$prefix_with_hyphen"
  fi
}

这非常适合“”、“字符串”和“a-字符串”:

echo $(get_prefix_with_hyphen "")

echo $(get_prefix_with_hyphen "string")

echo $(get_prefix_with_hyphen "a-string")
a-

但是,如果字符串中有两个或多个连字符,它将返回直到并包括 first 连字符的所有内容。我希望它包含所有内容,包括 last 连字符:

echo $(get_prefix_with_hyphen "a-long-string")
a-
# would like to return "a-long-"

如何在 sed 或其他工具中实现“贪婪”模式匹配?

函数中还有一个附加的“if”语句。是否可以删除它并以某种方式使用不同的正则表达式来达到相同的结果?

bash sed
1个回答
0
投票

从技术上讲,你的模式已经是贪婪的:

.*
尽可能多地匹配,这就是它消耗所有连字符的原因。

要使该模式非贪婪,您可以使用

-[^-]*$
来匹配连字符,后跟仅非连字符字符。

© www.soinside.com 2019 - 2024. All rights reserved.