7

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++

9
  • 1
    Just use /,/, without the /g?
    – Qtax
    Jul 18, 2013 at 23:10
  • Your regex works. So follow Qtax's advice
    – Valamas
    Jul 18, 2013 at 23:11
  • 4
    why not string.indexOf(',') ?
    – acdcjunior
    Jul 18, 2013 at 23:12
  • 1
    As @acdcjunior said, use string.indexOf(',') with a combination of substr or suchlike if possible, regex is slower.
    – The Alpha
    Jul 18, 2013 at 23:14
  • 1
    Why is @user1864610 being so obnoxious? Why not be helpful and friendly to people, even if they are doing something contrary to the conventions?
    – Rob Kent
    Feb 15, 2018 at 12:24

1 Answer 1

18

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

3
  • brilliant. how does this work? Jul 18, 2013 at 23:24
  • 3
    @Parseltongue: In the regex, (.*) means "zero or more non-newline characters -- and 'capture' them (i.e., remember them for later reference)". In the replacement-string, $1 means "the stuff you captured". (If you have multiple sets of (...), then you can also have $2, $3, etc.) So this works by replacing a comma, plus the rest of the line, with a colon, plus the rest of the line. After that, since the rest of the line has already undergone replacement, Notepad++ doesn't re-examine it to see if it contains a comma.
    – ruakh
    Jul 18, 2013 at 23:31
  • Thnaks so much for the explanation Jul 18, 2013 at 23:38

Not the answer you're looking for? Browse other questions tagged or ask your own question.