Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for matching just the first occurrence of a comma in each line [closed]

What does the regex look like for matching only the first instance of a comma, and nothing but that comma?

I have tried things like ,{1} and I think it has something to do with non-greedy qualifiers like this ,(.*?), but I have had no success.

I'm using Notepad++ to try to convert code from another language to JavaScript. I want to turn the first comma into a colon. It looks like this:

'TJ', 'Tajikistan' ,
'TZ', 'Tanzania' ,
'TH', 'Thailand' ,
'TL', 'Timor-Leste' ,
'TG', 'Togo' ,
'TK', 'Tokelau' ,
'TO', 'Tongo' ,
'TT', 'Trinidad and Tobago' ,

Find what: /,/
Replace with: :
0 occurrences were replaced

Screnshot of Notepad++

like image 763
Parseltongue Avatar asked Jul 18 '13 23:07

Parseltongue


1 Answers

What you can do is, instead of just replacing the first comma with a colon, you can automatically replace the comma and everything after it with the colon plus everything that was after the comma. (For example, in 'TZ', 'Tanzania' ,, this approach would replace , 'Tanzania' , with : 'Tanzania' ,.) After that, since the rest of the line has already undergone replacement, Notepad++ doesn't re-examine it to see whether it contains a comma.

The way you do that is by using a capture group, which lets the replacement-string incorporate part of what the regex matched.

Specifically, you would replace this ("Find what"):

,(.*)

meaning "a comma (,), plus zero or more characters (.*), and capture the latter (())", with this ("Replace with"):

:$1

meaning "a colon (:), plus whatever was captured by the first capture group ($1)".

like image 148
ruakh Avatar answered Oct 20 '22 04:10

ruakh