Python正则表达式中的"?:“字符组合

-1 投票
2 回答
549 浏览
提问于 2025-04-18 18:00

在Python的正则表达式中,?:是什么意思,当我们使用'或'的时候?

比如说,

(?:^|\n)可以在下面的文本中找到匹配的部分:

sample text sample text\nsample text sample text

但是(^|\n)就找不到。

这是为什么呢?

2 个回答

3

(?:) 被称为非捕获组,它只进行匹配操作,不会捕获任何内容。

>>> s = "sample text sample text\nsample text sample text"
>>> print s
sample text sample text
sample text sample text
>>> import re
>>> m = re.findall(r'(?:^|\n)', s, re.M) // In this re.findall function prints the matched characters(ie, two starts and a newline character).
>>> m
['', '\n', '']
>>> m = re.findall(r'(^|\n)', s, re.M) // In this re.findall function prints the captured characters.
>>> m
['', '\n', '']
4

(?: 是一个不捕获的分组

  (?:                      group, but do not capture:
    ^                        the beginning of the string
   |                        OR
    \n                       '\n' (newline)
  )                        end of grouping

可以看看这个 在线演示

想了解更多关于 捕获 的内容

如果你不需要这个分组来捕获匹配的内容,你可以把这个正则表达式优化成 (?:Value)。在开括号后面的问号和冒号是用来创建一个不捕获的分组的语法。

换句话说

(?:^|\n) Non-capturing group

 1st Alternative: ^
    ^ assert position at start of the string
 2nd Alternative: \n
    \n matches a fine-feed (newline) character (ASCII 10)

撰写回答