tags:

views:

43

answers:

4

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 (_)?

+1  A: 

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.

Recurse
A: 

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.

Josiah
That might work in the .NET or JGSoft flavors, but most flavors require the lookbehind expression to match substrings with a known, fixed length. Anyway, lookbehinds should never be your first resort; there's almost always a better way.
Alan Moore
Mmm good to know, thank you.
Josiah
+1  A: 

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.

Jonathan Leffler
A: 

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
ghostdog74