我需要一些关于声明正则表达式的帮助。我的输入如下:
我需要提取单词和单词之前的单词并在正则表达式中的“_”之间插入:python 输入
Input
s2 = 'Some other medical terms and stuff diagnosis of R45.2 was entered for this patient. Where did Doctor Who go? Then xxx feea fdsfd'
# my regex pattern
re.sub(r"(?:[a-zA-Z'-]+[^a-zA-Z'-]+){0,1}diagnosis", r"\1_", s2)
Desired Output:
s2 = 'Some other medical terms and stuff_diagnosis of R45.2 was entered for this patient. Where did Doctor Who go? Then xxx feea fdsfd'
请您参考如下方法:
您的正则表达式中没有定义捕获组,但正在使用 \1 占位符(替换反向引用)来引用它。
你想在单词diagnosis之前替换除-和'之外的1+个特殊字符,因此你可以使用
re.sub(r"[^\w'-]+(?=diagnosis)", "_", s2)
参见 this regex demo .
详情
[^\w'-]+- 任何非单词字符,不包括'和_(?=diagnosis)- 不消耗文本的正向前瞻(不添加到匹配值,因此re.sub不删除此部分文本),但只需要diagnosis文本立即出现在当前位置的右侧。
或者
re.sub(r"[^\w'-]+(diagnosis)", r"_\1", s2)
参见 this regex demo .这里,[^\w'-]+ 也匹配那些特殊字符,但是 (diagnosis) 是 capturing group可以使用 \1 placeholder 引用其文本来自替换模式。
注意:如果要确保 diagnosis 与整个单词匹配,请在其周围使用 \b,\bdiagnosis\b(注意 r 原始字符串文字前缀!)。
