复杂正则表达式的解释

2024-05-13 04:29:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些文本数据如下。你知道吗

{"Timestamp": "Tue Apr 07 00:32:29 EDT 2015",Title: Indian Herald: India's Latest News, Business, Sport, Weather, Travel, Technology, Entertainment, Politics, Finance <br><br>Product: Gecko<br>CPUs: 8<br>Language: en-GB"}

从下面的文本中,我使用以下正则表达式仅提取标题(Indian Herald: India's Latest News, Business, Sport, Weather, Travel, Technology, Entertainment, Politics, Finance):

appcodename = re.search(r'Title: ((?:(?!<br>).)+)', message).group(1)

我试图理解上面的正则表达式是如何工作的。你知道吗

(?!<br>)<br>的负前瞻

(?:(?!<br>).)+)-这是什么意思?有人能帮我把它分解一下吗。 另外,正则表达式中有多少捕获组。你知道吗


Tags: 文本brtitlebusinesslatestnewsindianweather
3条回答

你不需要这么复杂的正则表达式来获得标题。使用

Title:\s*(.*?)(?=\s*<br/?>)

demo

我们将Title:,然后将空格\s*,然后将tp <br/>上的任何字符与(.*?)(?=\s*<br/?>)匹配。你知道吗

至于(?:(?!<br>).)+,这意味着捕获一个或多个不跟在<br>后面的字符。有一个SO post where this construction is explained in detail。你知道吗

这里是来自regex101(转到Regex Debugger选项卡,然后单击右侧的+)的图像,显示了该构造正在执行的操作(检查下一个字符是否是<br>,如果不是,则消耗和回溯,等等):

enter image description here

关于正则表达式中有多少捕获组的问题,Title: ((?:(?!<br>).)+)有1个捕获组(((?:(?!<br>).)+))和1个非捕获组((?:(?!<br>).))。你知道吗

((?:(?!<br>).)+)的意思是:

((?:(?!<br>).)+)
^... Match the regex and capture its match into backreference 1

((?:(?!<br>).)+)
 ^... Match the regex (non capturing group)

((?:(?!<br>).)+)
    ^... Assert that it is not possible to match the regex <br>

((?:(?!<br>).)+)
            ^... Match a single character, that is not a line break character 

((?:(?!<br>).)+)
              ^... Between one and unlimmited times

首先,在这里你不需要向前看。您可以使用这个简单的正则表达式来完成所做的工作:

>>> re.search(r'Title: *(.+?) *<br>', message).group(1)
"Indian Herald: India's Latest News, Business, Sport, Weather, Travel, Technology, Entertainment, Politics, Finance"

顺便说一下你的正则表达式:

Title: ((?:(?!<br>).)+)

正在使用negative lookahead(?!<br>)在匹配文本Title:后的字符之前检查<br>是否存在。你知道吗

相关问题 更多 >