Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match everything up to the second occurrence of a character?

Tags:

regex

So my string looks like this:

Basic information, advanced information, super information, no information 

I would like to capture everything up to second comma so I get:

Basic information, advanced information 

What would be the regex for that?

I tried: (.*,.*), but I get

Basic information, advanced information, super information, 
like image 897
Micor Avatar asked Dec 03 '10 21:12

Micor


People also ask

How do you match a character except one?

To match any character except a list of excluded characters, put the excluded charaters between [^ and ] . The caret ^ must immediately follow the [ or else it stands for just itself. The character '. ' (period) is a metacharacter (it sometimes has a special meaning).


2 Answers

This will capture up to but not including the second comma:

[^,]*,[^,]* 

English translation:

  • [^,]* = as many non-comma characters as possible

  • , = a comma

  • [^,]* = as many non-comma characters as possible

[...] is a character class. [abc] means "a or b or c", and [^abc] means anything but a or b or c.

like image 131
Laurence Gonsalves Avatar answered Oct 08 '22 17:10

Laurence Gonsalves


You could try ^(.*?,.*?), The problem is that .* is greedy and matches maximum amount of characters. The ? behind * changes the behaviour to non-greedy.

You could also put the parenthesis around each .*? segment to capture the strings separately if you want.

like image 34
skajfes Avatar answered Oct 08 '22 17:10

skajfes