在正则表达式中组合paren和单词边界

2024-05-29 00:27:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字符串,其中包含几种类型的个人识别信息(PII):

text = 'Hello my name is Tom and I love Tomcat. My email address is tom@foo.bar and my phone number is (201) 5550123.'

我还有一个要从字符串中删除的PII列表:

values = ['Tom', 'tom@foo.bar', '(201) 5550123']

我希望将这些值组合到一个正则表达式中,并一次性替换它们,而不是在这些值上循环,一次替换一个:

escaped_values = [r'\b' + re.escape(value) + r'\b' for value in values]
combined_pattern = '|'.join(escaped_values)
combined_regex = re.compile(combined_pattern)

单词边界很重要,因为我不想把“Tom”从“Tomcat”中去掉,除非它自己出现。不管怎么说,除了电话号码之外,这几乎是可行的:

combined_regex.sub('', text)
# 'Hello my name is  and I love Tomcat. My email address is  and my phone number is (201) 5550123.'

我有点孤立这个问题。这与paren和单词边界的组合有关:

re.compile(r'\b\(201\)\ 5550123\b').sub('', 'before (201) 5550123 after')
# 'before (201) 5550123 after'

这不是Python的问题,从这里可以看出:

RegEx Pal showing PCRE mismatch

我知道有很多方法可以改变我的程序,但我不明白为什么这个正则表达式不起作用,它让我发疯


Tags: and字符串textnamerehelloismy
1条回答
网友
1楼 · 发布于 2024-05-29 00:27:49

您可以使用:

import re

text = 'Hello my name is Tom and I love Tomcat. My email address is tom@foo.bar and my phone number is (201) 5550123.'
values = ['Tom', 'tom@foo.bar', '(201) 5550123']
escaped_values = [re.escape(value) for value in values]
combined_pattern = r'(?<!\w)(?:' +'|'.join(escaped_values) + r')(?!\w)'
combined_regex = re.compile(combined_pattern)

print (combined_pattern)
print()
print (combined_regex.sub('', text))

输出:

(?<!\w)(?:Tom|tom@foo\.bar|\(201\)\ 5550123)(?!\w)

'Hello my name is  and I love Tomcat. My email address is  and my phone number is .'

注意此处使用的组合正则表达式:

(?<!\w)(?:Tom|tom@foo\.bar|\(201\)\ 5550123)(?!\w)

RegEx Demo

正则表达式解释:

  • (?<!\w):负查找,用于断言当前位置之前没有单词字符
  • (?::启动非捕获组
    • Tom|tom@foo\.bar|\(201\)\ 5550123:匹配其中一个子串,用|分隔(交替)
  • ):结束非捕获组
  • (?!\w):负前瞻,断言当前位置后没有单词字符

相关问题 更多 >

    热门问题