python-3.x - 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
我面临的当前问题是它显示无。
解决方案
如果要断言整个输入匹配[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']
推荐阅读
- python - 使用 selenium 和 xpath 单击提交按钮后如何从后续页面中提取节点?
- android - 如何修复这 5 个 Android SDK 编译错误?
- google-apps-script - 修改代码 - 将文件转换为 CSV。Google Apps 脚本/Google 表格
- c - C中的二维数组段错误
- javascript - NodeJs 的“子进程”如何与事件循环交互?
- angular - 无法从 rxjs observable 中提取数据
- sql - 需要死锁图解释帮助
- mysql - 如何在纯 SQL 中计算 Moodle 3.5 课程中组成员的角色?
- reactjs - 如何通过 JSX 中的 map/if 或三元运算符动态地将数据添加到表中
- r - powerBI中的自定义R视觉超时