匹配点的正则表达式

想知道从 "blah blah blah test.this@gmail.com blah blah"匹配 "test.this"的最佳方法是什么吗? 使用 Python。

我试过 re.split(r"\b\w.\w@")

360560 次浏览

正则表达式中的 .是元字符,用于匹配任何字符。要匹配原始 Python 字符串(r""r'')中的文字点,您需要转义它,因此 r"\."

在正则表达式中,需要使用点 逃跑或者在 性格类 "[.]"中使用它,因为它是正则表达式中的元字符,可以匹配任何字符。

另外,需要使用 \w+而不是 \w来匹配一个或多个单词字符。


现在,如果您想要 test.this内容,那么 split不是您所需要的。split将沿着 test.this分割你的字符串。例如:

>>> re.split(r"\b\w+\.\w+@", s)
['blah blah blah ', 'gmail.com blah blah']

你可以使用 re.findall:

>>> re.findall(r'\w+[.]\w+(?=@)', s)   # look ahead
['test.this']
>>> re.findall(r'(\w+[.]\w+)@', s)     # capture group
['test.this']

”在默认模式下,点(.)匹配除换行符之外的任何字符。如果指定了 DOTALL 标志,则匹配包括换行符在内的任何字符。”(巨蟒文件)

所以,如果你想从字面上计算点,我认为你应该把它放在方括号里:

>>> p = re.compile(r'\b(\w+[.]\w+)')
>>> resp = p.search("blah blah blah test.this@gmail.com blah blah")
>>> resp.group()
'test.this'

在 javascript 中,你必须使用 \\.来匹配一个点。

例子

"blah.tests.zibri.org".match('test\\..*')
null

还有

"blah.test.zibri.org".match('test\\..*')
["test.zibri.org", index: 5, input: "blah.test.zibri.org", groups: undefined]

这个表情,

(?<=\s|^)[^.\s]+\.[^.\s]+(?=@)

对于那些特定类型的输入字符串也可以正常工作。

演示

测试

import re


expression = r'(?<=^|\s)[^.\s]+\.[^.\s]+(?=@)'
string = '''
blah blah blah test.this@gmail.com blah blah
blah blah blah test.this @gmail.com blah blah
blah blah blah test.this.this@gmail.com blah blah
'''


matches = re.findall(expression, string)


print(matches)

输出

['test.this']

如果您希望简化/修改/探索这个表达式,它已经在 Regex101.com的右上面板中进行了解释。如果您愿意,您还可以在 这个链接中观察它如何与一些样本输入进行匹配。


要转义字符串变量(包括点)的非字母数字字符,可以使用 re.escape:

import re


expression = 'whatever.v1.dfc'
escaped_expression = re.escape(expression)
print(escaped_expression)

产出:

whatever\.v1\.dfc

可以使用转义表达式逐字地查找/匹配字符串。

这是我对 主要答案@Yuushi的附加功能:

摘要

这些是不允许的。

'\.'   # NOT a valid escape sequence in **regular** Python single-quoted strings
"\."   # NOT a valid escape sequence in **regular** Python double-quoted strings

他们会发出这样的警告:

无效转义序列 \.

然而,所有这些都是允许的,并且是等价的:

# Use a DOUBLE BACK-SLASH in Python _regular_ strings
'\\.'  # **regular** Python single-quoted string
"\\."  # **regular** Python double-quoted string


# Use a SINGLE BACK-SLASH in Python _raw_ strings
r'\.'  # Python single-quoted **raw** string
r"\."  # Python double-quoted **raw** string

解释

请记住,如果在常规字符串('some string'"some string")中而不是在 未经处理的字符串(r'some string'r"some string")中使用,则反斜杠(\)字符本身必须在 Python 中转义。因此,请记住您正在使用的字符串类型。因此,要在正则 Python 字符串中转义正则表达式中的点或句点(.) ,还必须使用双反斜杠(\\)转义反斜杠,使正则表达式中 .的总转义序列为 this: \\.,如上面的示例所示。

参考文献

  1. 主要和官方参考文献: < a href = “ https://docs.python.org/3/REFERENCE/lexical _ analysis.html # string-AND-bytes-Literals”rel = “ nofollow noReferrer”> https://docs.python.org/3/REFERENCE/lexical_analysis.html#string-AND-bytes-literals enter image description here
  2. 如何修复 Python 中的“无效转义序列”?

    如果要在字符串中放入字面 \,则必须使用 \\