无法让正则表达式正确处理括号

2024-05-21 15:19:14 发布

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

为这个模糊的标题道歉

我想找一个正则表达式来搜索并确定如下内容:

"Brand New Song [Demonstration]"

通过使用re.search()在字符串的某处找到“[Demonstration]”。下面是一个我认为应该返回True的示例:

bool (re.search (r"\b\[Demonstration\]\b", "Brand New Song [demonstration]", re.IGNORECASE))

更简单的是,它也返回False:

bool (re.search (r"\b\[\b", " [ "))

我一直使用\b作为捕获字符串的开头和结尾,因为它应该表示单词(as per documentation here))开头或结尾的任何空格字符串,我看不出我搞砸了什么

继续迷惑,以下返回True:

bool (re.search (r"\b\[\b", "_[_"))

这同样令人困惑,因为\b定义为“…空格或非字母数字、非下划线字符。”所以,请帮我找出我可能遗漏的愚蠢细节,谢谢


Tags: 字符串retrue标题示例内容newsearch
1条回答
网友
1楼 · 发布于 2024-05-21 15:19:14

您需要从模式中删除单词边界\b

>>> import re
>>> s = 'Brand New Song [demonstration]'
>>> bool(re.search (r'\[Demonstration\]', s, re.IGNORECASE))
True

单词边界不使用任何字符,它断言在一侧有单词字符,而在另一侧没有。如regular-expressions.info documentation中所述:

There are three different positions that qualify as word boundaries:

  • Before the first character in the string, if the first character is a word character.
  • After the last character in the string, if the last character is a word character.
  • Between two characters in the string, where one is a word character and the other is not a word character.

相关问题 更多 >