首页 > 解决方案 > python正则表达式匹配单词

问题描述

我正在尝试检查 desc 是否以 [ab] 开头并打印出 desc

import re
desc = "[ab] test"
match = re.search(r"(?<=\[ab\] ).*", desc)
if match != None:
  print(match.group())

预期的输出是:

[ab] test

它应该匹配:

[ab] apple
[ab] pear

它不应该匹配:

ab apple
[a] apple

我面临的当前问题是它显示无。

标签: python-3.xregex

解决方案


如果要断言整个输入匹配[ab] something,则使用re.search锚点:

desc = "[ab] test"
if re.search(r'^\[ab\] \S+$', desc):
    print("MATCH")
else:
    print("NO MATCH")

如果要从较大的文本中提取此类匹配项,请使用re.findall

inp = "ab apple [a] apple [ab] apple blah [ab] pear"
matches = re.findall(r'\[ab\] \S+', inp)
print(matches)  # ['[ab] apple', '[ab] pear']

推荐阅读