我测试了我的代码,以确保我的模式与测试用例test匹配,但由于某种原因,它在文本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))发布于 2020-02-20 12:14:18
您的正则表达式^...$中有锚点,它断言匹配需要是整个字符串(从头到尾)。整个字符串显然不是一个匹配候选字符串(您知道这一点,否则您就不会尝试使用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})?)?')https://stackoverflow.com/questions/60312773
复制相似问题