【问题标题】:python regex to match wordspython正则表达式匹配单词
【发布时间】:2021-04-12 04:37:24
【问题描述】:

我正在尝试检查 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 脚本甚至无法毫无错误地编译/解析。请包含您正在运行的实际脚本以及一些示例数据。
  • @CinCout 目前正在打印无。如果匹配,预期的结果是打印出 desc。
  • @TimBiegeleisen 添加了详细信息
  • re.search(r"(?&lt;=\[ab\] ).*", desc) 应该可以正常工作,有什么问题?

标签: python-3.x regex


【解决方案1】:

如果您想断言整个输入与[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']

【讨论】:

  • 嗨,蒂姆,使用 re.search 匹配“[ab] apple pear”怎么样? @蒂姆·比格莱森
  • 这听起来像是另一个问题的良好起点(虽然不是你在这里问的)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-06-10
  • 2015-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-14
相关资源
最近更新 更多