python - 正则表达式模式不打印文本中的匹配项
问题描述
我测试了我的代码以确保我的模式与测试用例匹配,test
但由于某种原因,它没有在 text 字符串中找到匹配项text_to_search
。有谁可以帮我离开这里吗?起初我以为我修复了它,因为我忘记了使用.group(0)
打印完整匹配但它仍然无法正常工作。
这是我的代码:
test = 'E000.1'
text_to_search = '''
237.0-237.2 is the range for the ICD-9 codes for neoplasm of uncertain behavior of\
endocrine glands and nervous system. On the hand, the ICD-9 code for Type II Diabetes\
with other manifestations is 250.8x where x is 0 or 2 depending on controlled or\
uncontrolled.
'''
pattern = re.compile(r'^(V\d{2}(\.\w{1,3})?|\d{3}(\.\w{1,2})?|E\d{3}(\.\w{1,2})?)-?(V\d{2}(\.\w{1,3})?|\d{3}(\.\w{1,2})?|E\d{3}(\.\w{1,2})?)?$')
matches = pattern.finditer(text_to_search)
for match in matches:
print(matches.group(0))
解决方案
您的正则表达式中有锚点,^...$
它断言匹配需要是整个字符串(从开始到结束)。整个字符串显然不是匹配候选者(您知道,否则您不会尝试使用 查找多个匹配项finditer
)。
移除那些锚。
pattern = re.compile(r'(V\d{2}(\.\w{1,3})?|\d{3}(\.\w{1,2})?|E\d{3}(\.\w{1,2})?)-?(V\d{2}(\.\w{1,3})?|\d{3}(\.\w{1,2})?|E\d{3}(\.\w{1,2})?)?')
推荐阅读
- c++ - OpenMP 编译错误:“reduction”对“#pragma omp taskloop”无效
- dart - 在飞镖中克隆一个新地图
- intellij-idea - 在 intellij 中固定时缩小标签大小
- sql - 调整存储过程
- python - Pandas:将数据框旋转到每个用户(组)一行
- hmac - 使用带有汇总的旧 Require 模块
- html - Angular Material 车身高度 100%
- c# - 如何使用 Interop Word 选择页面的最后一个字符?
- firebase-realtime-database - 类型错误:无法读取未定义的属性“文本”
- javascript - Console.log() 不将 DOM 元素显示为对象?