开发者

Can I write this regex in one step?

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.


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

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

with

" $1 "

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


I'd try

Regex.Replace(input, @"\s*[+-]\s*", m => " " + m.ToString().Trim() + " ");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜