使用 Bash 的惰性正则表达式

sal*_*ace 4 bash regular-expression

我正在尝试使用 Bash 的内置正则表达式函数仅匹配 HTML 标签中包含的文本:

string='<span class="circle"> </span>foo</span></span>'
regex='<span class="circle"> </span>(.+?)</span>'
[[ $string =~ $regex ]]
echo "${BASH_REMATCH[1]}"
Run Code Online (Sandbox Code Playgroud)

但比赛不断捕获foo</span>

互联网上充斥着 sed 和 grep 的例子,我在 Bash 自己的正则表达式上找不到太多文档。

ter*_*don 10

互联网上充斥着替代方法是有原因的。我真的想不出任何情况下您会被迫为此使用 bash。为什么不使用为这项工作设计的工具之一?

无论如何,据我所知,无法使用=~运算符进行非贪婪匹配。那是因为它不使用 bash 的内部正则表达式引擎,而是使用系统的 C 引擎,如man 3 regex. 这在man bash

   An additional binary operator, =~, is available, with the  same  prece?
   dence  as  ==  and !=.  When it is used, the string to the right of the
   operator is considered  an  extended  regular  expression  and  matched
   accordingly  (as  in  regex(3)).  
Run Code Online (Sandbox Code Playgroud)

但是,您可以使用稍微不同的正则表达式或多或少地做您想做的事情(请记住,这确实不是解析 HTML 文件的好方法):

string='<span class="circle"> </span>foo</span></span>'
regex='<span class="circle"> </span>([^<]+)</span>'
[[ $string =~ $regex ]]; 
echo "${BASH_REMATCH[1]}"
Run Code Online (Sandbox Code Playgroud)

以上将按foo预期返回。