0

正则表达式:

<span style='.+?'>TheTextToFind</span>

HTML:

<span style='font-size:11.0pt;'>DON'T_WANT_THIS_MATCHED <span style='font-size:18.0pt;'>TheTextToFind</span></span>

为什么比赛包括这个?

<span style='font-size:11.0pt;'>DON'T_WANT_THIS_MATCHED

示例链接

4

1 回答 1

5

正则表达式引擎总是找到最左边的匹配项。这就是为什么你得到

<span style='font-size:11.0pt;'>DON'T_WANT_THIS_MATCHED <span style='font-size:18.0pt;'>TheTextToFind</span>

作为比赛。(基本上是整个输入,没有最后一个</span>)。

为了将引擎引导到正确的方向,如果我们假设它>没有直接出现在属性中,则以下正则表达式将匹配您想要的。

<span style='[^>]+'>TheTextToFind</span>

此正则表达式与您想要的匹配,因为根据上述假设,[^>]+无法匹配标签之外的内容。

但是,我希望您不要将其作为从 HTML 页面中提取信息的程序的一部分。为此目的使用 HTML 解析器。


要了解正则表达式为何如此匹配,您需要了解.+?它将尝试回溯,以便它可以找到与续集( '>TheTextToFind</span>) 匹配的内容。

# Matching .+?
# Since +? is lazy, it matches . once (to fulfill the minimum repetition), and
# increase the number of repetition if the sequel fails to match
<span style='f                        # FAIL. Can't match closing '
<span style='fo                       # FAIL. Can't match closing '
...
<span style='font-size:11.0pt;        # PROCEED. But FAIL later, since can't match T in The
<span style='font-size:11.0pt;'       # FAIL. Can't match closing '
...
<span style='font-size:11.0pt;'>DON'  # PROCEED. But FAIL later, since can't match closing >
...
<span style='font-size:11.0pt;'>DON'T_WANT_THIS_MATCHED <span style='
                                      # PROCEED. But FAIL later, since can't match closing >
...
<span style='font-size:11.0pt;'>DON'T_WANT_THIS_MATCHED <span style='font-size:18.0pt;
                                      # PROCEED. MATCH FOUND.

如您所见,.+?尝试增加 length 和 matches font-size:11.0pt;'>DON'T_WANT_THIS_MATCHED <span style='font-size:18.0pt;,这允许匹配续集 '>TheTextToFind</span>

于 2014-02-12T16:12:15.133 回答