[英]Exact string match with parantheses
我一直在使用單詞邊界來查找字符串中的確切單詞,但只是了解到它們忽略了非單詞字符。
因此,當我在字符串“height(in stories)”中查找“height”時,我得到了我期望的結果:
p = re.compile(r'\b%s\b' % 'height')
p.search('height (in stories)') # match
但是當我在字符串“height(in stories)”中查找“height(in stories)”時,我沒有得到匹配:
p = re.compile(r'\b%s\b' % 'height (in stories)')
p.search('height (in stories)') # no match
如何識別括號?
有兩個問題。
re.escape(text)
來創建與字符串text
匹配的正則表達式。 p = re.compile(r'\\bheight \\(in stories\\)')
使用正則表達式時,您應該閱讀它們的語法 。
(
和)
字符在正則表達式中具有特殊含義,如果要按字面匹配字符,則需要轉義它們。 就像點.
...
考慮使用re.escape
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.