Matching only the first occurrence in a line with Regex

The matching pattern could be:

^([^,]+),

That means

^        starts with
[^,]     anything but a comma
+        repeated one or more times (use * (means zero or more) if the first field can be empty)
([^,]+)  remember that part
,        followed by a comma

In e.g. perl, the whole match and replace would look like:

s/^([^,]+),/\1 /

The replacement part just takes the whole thing that matched and replaces it with the first block you remembered and appends a space. The coma is "dropped" because it's not in the first capturing group.


s/,/ /

This, by default (i.e. without the g option), replaces only the first match.


This should match only the first number and the comma: ^(\d{5}),. If you'd like to gobble up everything else in the line, change the regex to this: ^(\d{5}),(.*)$

Tags:

Regex