Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

?: Notation in Regular Expression [duplicate]

Tags:

regex

People also ask

What is ?: In regex?

'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.)

How do you match duplicate words in regex?

Following example shows how to search duplicate words in a regular expression by using p. matcher() method and m. group() method of regex. Matcher class.

What does * do in regular expression?

The Match-zero-or-more Operator ( * ) This operator repeats the smallest possible preceding regular expression as many times as necessary (including zero) to match the pattern.


This is going to be short answer.

When you use (?:) it means that the group is matched but is not captured for back-referencing i.e non-capturing group. It's not stored in memory to be referenced later on.

For example:

(34)5\1

This regex means that you are looking for 34 followed by 5 and then again 34. Definitely you could write it as 34534 but sometimes the captured group is a complex pattern which you could not predict before hand.

So whatever is matched by capturing group should be appearing again.

Regex101 demo for back-referencing


Back-referencing is also used while replacement.

For Example:

([A-Z]+)[0-9]+

This regex will look for many upper case letters followed by many digits. And I wish to replace this whole pattern just by found upper case letters.

Then I would replace whole pattern by using \1 which stands for back-referencing first captured group.

Regex101 demo for replacement

If you change to (?:[A-Z]+)[0-9]+ this will no longer capture it and hence cannot be referenced back.

Regex101 demo for non-capturing group

A live answer.


It's called a 'non-capturing group', which means the regex would not make a group by the match inside the parenteses like it would otherwise do (normally, a parenthesis creates a group).