views:

47

answers:

2

This is the input string "23x +y-34 x + y+21x - 3y2-3x-y+2". I want to surround every '+' and '-' character with whitespaces but only if they are not allready sourrounded from left or right side. So my input string would look like this "23x + y - 34 x + y + 21x - 3y2 - 3x - y + 2". I wrote this code that does the job:

    Regex reg1 = new Regex(@"\+(?! )|\-(?! )");
    input = reg1.Replace(input, delegate(Match m) { return m.Value + " "; });
    Regex reg2 = new Regex(@"(?<! )\+|(?<! )\-");
    input = reg2.Replace(input, delegate(Match m) { return " " + m.Value; });

explanation: reg1 // Match '+' followed by any character not ' ' (whitespace) or same thing for '-'

reg2 // Same thing only that I match '+' or '-' not preceding by ' '(whitespace)

delegate 1 and 2 just insert " " before and after m.Value ( match value )

Question is, is there a way to create just one regex and just one delegate? i.e. do this job in one step? I am a new to regex and I want to learn efficient way.

+6  A: 

I don't see the need of lookarounds or delegates here. Just replace

\s*([-+])\s*

with

" $1 "

(See http://ideone.com/r3Oog.)

KennyTM
Nice site, ideone.com!
Bart Kiers
thx, I am a new to regex, didn't know that it can be that simple
dontoo
+3  A: 

I'd try

Regex.Replace(input, @"\s*[+-]\s*", m => " " + m.ToString().Trim() + " ");
Jens
Lambda expressions are fun, but this can be done with regexes alone, as @KennyTM demonstrated.
Alan Moore