tags:

views:

55

answers:

3

It is necessary regexp to replace in a line of a colon with blanks, excepting situations where a colon the first and (or) last symbol - them is simply deleted.

Example1
"6:206:НР" -> "6 206 НР"

Example2
":206:" -> "206"

+1  A: 

You can't do conditional replacement with a single regex alone. You'll need to use your language's library. Python example:

s = s.replace(':', ' ').strip()

If you absolutely need to do it through regex, you can use two of them. Example:

s = re.sub(':', ' ', re.sub('^:|:$', '', s))
Max Shawabkeh
+2  A: 

In PHP you can do:

$from = array('/^:|:$/','/:/');
$to = array('',' ');
$output = preg_replace($from,$to,$input);
codaddict
Three great answers so far, but if it were up to me, I would accept this one. I think it expresses your intent more clearly than the others, and it can be adapted easily to replace the colon with something other than a space, should you need that.
Alan Moore
+2  A: 

It's hardly necessary to use regular expressions for such a trivial task. Replace all colons with spaces first, then trim the resulting string to get rid of spaces before and after the data.

PHP Syntax:

$string = trim(str_replace(':', ' ', $string));
Rowlf
What if the input is " abc ", your regex will trim the spaces.
codaddict
Ah, but I'm not trying to solve a problem the OP doesn't have :). For all I know the strings that need converting consist of alphanumeric characters + the colon. The phrasing of the question suggests that the OP _does_ want the spaces around the data trimmed, or else he would have been happy with " 206 " in the second example.
Rowlf