x Hint: Register, if you want to hide ads.
x Did you like it? Well, then please consider making a donation :)

Regex Tag - group

Get IP address - simple non capturing example

?: is used when you want to group an expression, but you do not want to save it as a matched/captured portion of the string. An example would be something to match an IP address: (?:\d{1,3}\.){3}\d{1,3} Note that I don't care about saving the first 3 octets, but the (?:...) grouping allows me to shorten the regex without incurring the overhead of capturing and storing a match.

Type: match, Date: 7/12/2015 3:29:13 PMAuthor: stackoverflow

Simple example - non capturing group

If I apply the regex below over it: (http|ftp)://([^/\r\n]+)(/[^\r\n]*)? I would get the following result: Match "http://stackoverflow.com/" Group 1: "http" Group 2: "stackoverflow.com" Group 3: "/" But I don't care about the protocol - I just want the host and path of the URL. So, I change the regex to include the non-capturing group (?:): (?:http|ftp)://([^/\r\n]+)(/[^\r\n]*)? Now, my result looks like this: Match "http://stackoverflow.com/" Group 1: "stackoverflow.com" Group 2: "/"

Type: match, Date: 7/12/2015 3:23:20 PMAuthor: stackoverflow

Replace and named capturing group example

Nearly all modern regular expression engines support numbered capturing groups and numbered backreferences. Long regular expressions with lots of groups and backreferences may be hard to read. They can be particularly difficult to maintain as adding or removing a capturing group in the middle of the regex upsets the numbers of all the groups that follow the added or removed group.

Type: replace, Date: 3/30/2015 2:35:04 AMAuthor: admin