Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/286.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python正则表达式是否匹配_Python_Regex - Fatal编程技术网

Python正则表达式是否匹配

Python正则表达式是否匹配,python,regex,Python,Regex,出于某种原因 m = re.search('(<[^pib(strong)(br)].*?>|</[^pib(strong)]>)', '</b>') m=re.search(‘(|)’,“”) 匹配字符串,但是 m = re.search('(</[^pib(strong)]>)', '</b>') m=re.search(“()”,“) 没有。我正在尝试匹配所有不匹配的标记 ,, 等等。我是否误解了“|”的工作原理?你做错

出于某种原因

m = re.search('(<[^pib(strong)(br)].*?>|</[^pib(strong)]>)', '</b>')
m=re.search(‘(|)’,“”)
匹配字符串,但是

m = re.search('(</[^pib(strong)]>)', '</b>')
m=re.search(“()”,“)
没有。我正在尝试匹配所有不匹配的标记


等等。我是否误解了“|”的工作原理?

你做错了。首先,
[]
之间的字符匹配方式不同:
[ab]
将匹配
a
b
,因此在您的情况下,
[^pib(strong)]
将匹配所有不是a
p
、a
i
、a
b
、a
)的字符(请注意
^/code>中的否定).你的第一个正则表达式匹配只是巧合

另外,您不应该使用正则表达式解析html/xml,而是使用适当的xml解析库,如lxml或beautifulsoup

下面是一个使用
lxml
的简单示例:

from lxml import html
dom = html.fromstring(your_code)
illegal = set(dom.cssselect('*')) - set(dom.cssselect('p,b'))
for tag in illegal:
    do_something_with(tag)
(这是一个小的,可能是次优的示例;它只是向您展示了使用这样一个库是多么容易。另外,请注意,库会将代码包装在一个
中,因此您应该考虑到这一点)

from lxml import html
dom = html.fromstring(your_code)
illegal = set(dom.cssselect('*')) - set(dom.cssselect('p,b'))
for tag in illegal:
    do_something_with(tag)