I have this string:-
ABCDE/Something something:XYZ=0, JKLM=0/SOMETHING Something:some_value
What is the regex so that only the first colon (:) is replaced with underscore (_)?
I have this string:-
ABCDE/Something something:XYZ=0, JKLM=0/SOMETHING Something:some_value
What is the regex so that only the first colon (:) is replaced with underscore (_)?
Just match two groups - the first being everything before the first colon; the second, everything after it. Then just rebuild the string with the underscore in place.
s/([^:]*):(.*)/\1_\2/
You will need differing escaping depending on the language/regex-engine you use.
You can do it in regex using a negative lookbehind, but that's relatively inefficient:
(?<!:.*):
Will only match a colon if no other colon has been previously matched.
However, since you're only replacing one character, not a pattern of characters, I would suggest using the language's native "replace" function. You'll get better performance and readability.
In standard systems, you simply write:
s/:/_/
To achieve a global replace (replacing every instance of colon with underscore) you'd add a qualifier (often 'g') after the substitution.
Different languages use different notations for regular expressions, so the detailed answer depends on the target language. However, what I wrote works in 'sed', 'ed', 'vi', 'vim', and Perl.
if you are on *nix and have tools like sed
$ echo "ABCDE/Something something:XYZ=0, JKLM=0/SOMETHING Something:some_value" | sed 's/:/_/'
ABCDE/Something something_XYZ=0, JKLM=0/SOMETHING Something:some_value
also, if you are using bash as your shell
$ var="ABCDE/Something something:XYZ=0, JKLM=0/SOMETHING Something:some_value"
$ echo ${var/:/_}
ABCDE/Something something_XYZ=0, JKLM=0/SOMETHING Something:some_value