“?:”python正则表达式中的字符组合

时间:2014-08-21 04:41:03

标签: python regex

?:在使用'或'时的含义在python正则表达式?

e.g

(?:^|\n)确实按照文字

来捕捉匹配
sample text sample text\nsample text sample text

(^|\n)没有。

这是什么原因?

2 个答案:

答案 0 :(得分:4)

(?:是非捕获组

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

查看online demo

详细了解Capturing

  

如果您不需要该组捕获其匹配项,则可以将此正则表达式优化为(?: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)

答案 1 :(得分:2)

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

>>> 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', '']