58

I have a regex that looks like this

/^(?:\w+\s)*(\w+)$*/

What is the ?:?

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Bimmy
  • 690
  • 1
  • 5
  • 6

4 Answers4

59

It indicates that the subpattern is a non-capture subpattern. That means whatever is matched in (?:\w+\s), even though it's enclosed by () it won't appear in the list of matches, only (\w+) will.

You're still looking for a specific pattern (in this case, a single whitespace character following at least one word), but you don't care what's actually matched.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
15

It means only group but do not remember the grouped part.

By default ( ) tells the regex engine to remember the part of the string that matches the pattern between it. But at times we just want to group a pattern without triggering the regex memory, to do that we use (?: in place of (

codaddict
  • 445,704
  • 82
  • 492
  • 529
  • 6
    it's still confusing to me...can you provide some simple example ? – Beeing Jk Aug 03 '18 at 10:40
  • Look at the answer to the following question: [non-capturing groups](https://stackoverflow.com/questions/3512471/what-is-a-non-capturing-group-in-regular-expressions) – Humza Naveed Apr 19 '22 at 10:47
9

Further to the excellent answers provided, its usefulness is also to simplify the code required to extract groups from the matched results. For example, your (\w+) group is known as group 1 without having to be concerned about any groups that appear before it. This may improve the maintainability of your code.

Ardent Coder
  • 3,777
  • 9
  • 27
  • 53
Christopher Hunt
  • 2,071
  • 1
  • 16
  • 20
1

Let's understand by taking a example

In simple words we can say is let's for example I have been given a string say (s="a eeee").

Your regex(/^(?:\w+\s)(\w+)$/. ) will basically do in this case it will start with string finds 'a' in beginning of string and notice here there is 'white space character here) which in this case if you don't included ?: it would have returned 'a '(a with white space character).

If you may don't want this type of answer so u have included as*(?:\w+\s)* it will return you simply a without whitespace ie.'a' (which in this case ?: is doing it is matching with a string but it is excluding whatever comes after it means it will match the string but not whitespace(taking into account match(numbers or strings) not additional things with them.)

PS:I am beginner in regex.This is what i have understood with ?:.Feel free to pinpoint the wrong things explained.