首页 > 解决方案 > 正则表达式模式不打印文本中的匹配项

问题描述

我测试了我的代码以确保我的模式与测试用例匹配,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))

标签: pythonregex

解决方案


您的正则表达式中有锚点,^...$它断言匹配需要是整个字符串(从开始到结束)。整个字符串显然不是匹配候选者(您知道,否则您不会尝试使用 查找多个匹配项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})?)?')

推荐阅读