3

Possible Duplicate:
Non capturing group?

From python re module document, i see:

(?:...)  Non-grouping version of regular parentheses.

and

(...)    Matches the RE inside the parentheses.
         The contents can be retrieved or matched later in the string.

What's differece?

Community
  • 1
  • 1
user1365596
  • 81
  • 2
  • 6
  • The description is not very accurate in imo. `(?:...)` still "groups" the inner expression in a way (think about `(?:...)+`, the quantifier is applied to the while group), but you cannot reference the matched content later on, because it is not captured. – Felix Kling Apr 30 '12 at 10:40

3 Answers3

5

shortly: Non-grouping means it will not be matched into a group. that is, you cannot reference it by \1 for example.

Kent
  • 189,393
  • 32
  • 233
  • 301
1

The difference is basically what Kent said.

It might be useful for very complex regexes, or when applying to large amounts of text where performance is crucial.

Also, if you use a lot of grouping in your regex, but only some of them are to be referenced after (for text replacement or whatever reason), then it's simpler to have only the ones you really need as capturing groups, so you can refer to then from \1 (or $1, depends), to \n, instead of skipping numbers.

pcalcao
  • 15,789
  • 1
  • 44
  • 64
0

Non-grouping allows you to use a sequence of characters in your match string without it being returned as one of your actual match terms. As an example, let's say you were searching a receipt, and you only wanted to pull prices for items. Say your receipt looks like:

milk 1.25
bread 1.15
deli meat 5.25
total 7.65

You could use a non-grouping paren to exclude the line with a price that said total but capture all the other prices.

Silas Ray
  • 25,682
  • 5
  • 48
  • 63
  • 1
    I think you're confusing non-capturing groups with lookarounds. Non-capturing groups do become part of the match, you just can't access their contents via a backreference. – Tim Pietzcker Apr 30 '12 at 11:06
  • @TimPietzcker Depends how you are using them. I'm pretty sure at least in Python's regex engine, non-grouping matches won't show up in `.groups()`, so if you are doing a `findall()` or something, it will effectively behave as I describe. – Silas Ray Apr 30 '12 at 11:42
  • @sr2222 but it will show up in .group(0), which contains the entire match. – jordanm Apr 30 '12 at 17:08