Regex,使用单词边界捕获而不在 \\”dot\\” 和/或其他字符处停止
•浏览 1
Regex, capture using word boundaries without stopping at "dot" and/or other characters
例如给定这样的字符串:
随机词,随机字符##?,一些点。用户名 bob.1234 其他东西
我目前正在使用这个正则表达式来捕获用户名(bob.1234):
\\busername (.+?)(,| |$)
\\busername (.+?)\\b
但是我的代码需要一个只有一个捕获组的正则表达式,因为当有多个捕获组时,python 的 re.findall 返回不同的东西。像这样的东西几乎可以工作,除了它会捕获用户名"bob"而不是"bob.1234":
\\busername (.+?)(,| |$)
\\busername (.+?)\\b
有人知道是否有一种方法可以使用单词边界同时忽略点并且不使用多个捕获组?
注意事项:
- 有时用户名后面有逗号
- 有时用户名后面有一个空格
- 有时字符串以用户名结尾
\\busername (.+?)(,| |$) 模式包含 2 个捕获组,一旦找到匹配项,re.findall 将返回一个元组列表。请参阅 findall 参考:
If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result unless they touch the beginning of another match.
所以,这里有三种方法:
- 使用 (?:...) 非捕获组而不是捕获组:re.findall(r'\\busername (.+?)(?:,| |$)', s)。它将消耗一个 , 或空间,但由于只返回捕获的部分并且预计不会重叠匹配,所以没关系。
- 请改用积极的前瞻:re.findall(r'\\busername (.+?)(?=,| |$)', s)。不会消耗空格和逗号,这是与第一种方法的唯一区别。
- 您可以将 (.+?)(,| |$) 变成一个简单的否定字符类 [^ ,]+,它匹配一个或多个字符而不是空格或逗号。如果 , 或 username 之后没有空格,它将匹配到字符串末尾。