使用正则表达式排除字符串?

时间:2017-02-04 18:07:52

标签: python regex

我收到了一些电子邮件

info@gmail.com
epd@omi.ru
salesall@finteca.ru

我需要忽略包含info, sales的字符串,所以我使用了pattern:

'/(?!spb)[a-zA-Z0-9-_\.]+@[a-z0-9\.]+$'

但它会返回[]。我做错了什么?

3 个答案:

答案 0 :(得分:0)

https://regex101.com/r/505NB9/1看起来不需要前两个字符。

答案 1 :(得分:0)

请参阅下面的工作示例。

  • 为了让您的代码正常运行,您还需要包含^来表示行的开头。
  • 您获得[]的原因可能是因为您没有使用re.MULTILINE选项。 re.MULTILINE标志告诉python使'^'和'$'特殊字符匹配字符串中任何行的开头或结尾,而不是整个字符串的开头或结尾。

Visual representation of the required regular expression

import re

test = 'info@gmail.com\nepd@omi.ru\nsalesall@finteca.ru'
print(test)

info@gmail.com
epd@omi.ru
salesall@finteca.ru

pattern = re.compile('^(?!info|sales)[[a-zA-Z0-9-_.]+@[a-z0-9.]+$', re.MULTILINE)
emails = re.findall(pattern, test)
print(emails)

['epd@omi.ru']

答案 2 :(得分:0)

也许更容易理解和维护:

import re

string = """
info@gmail.com
epd@omi.ru
salesall@finteca.ru

some other text here with emails email@email.com included"""

rx = re.compile(r'\S+@\S+')

def ignore(value):
  lst = ['info', 'sales']
  for i in lst:
    if i in value:
      return False
  return True

emails = filter(ignore, rx.findall(string))
print(emails)
# ['epd@omi.ru', 'email@email.com']

只需根据需要调整lst ignore()