tags:

views:

273

answers:

5

I tried to replace   elements in a string using .NET regex - with no luck :)

Assume the following string:

 AA A  C D   A Some Text   here

The rules

  1. Do not replace at beginning of line
  2. Do only replace single occurrences
  3. Do not replace if a space is before or after it (optional)

The desired result from above is (# as replacement character):

 AA#A  C#D   A#Some Text   here

+1  A: 

I am not familiar with C#'s particular regex flavor but in PERL/PHP style this works for me:

s/(?<!\A| |&nbsp;)&nbsp;(?!&nbsp;| )/#/g

This relies on negative lookbehind, negative lookahead and the \A = start of input escape sequence.

beggs
Would (with some modifications) work - thanks.I choose Ahmads answer since it solves the whole problem.
ManniAT
+1  A: 

string s = Regex.Replace(original, "(?<!(&nbsp;| |^))&nbsp;(?!(&nbsp;| ))", "#");

LukeH
yea I had the same problem... use the back tick not the 4 space indention.
beggs
@beggs: Thanks, was just trying to figure that out. Will edit.
LukeH
You could shorten it further to `(?<! | |^) (?! | )`
Tim Pietzcker
A: 

You may use this one

[^^\s(nbsp;)](nbsp;)[^$\s(nbsp;)]
Cem Kalyoncu
+2  A: 

This should cover all 3 of your requirements. Excuse the formatting; I had to back-tick the first few lines for the &nbsp; to show up properly.

string pattern = @"(?<!^|&nbsp;)((?<!\s)&nbsp;(?!\s))(?!\1)";

string[] inputs = { "&nbsp;AA&nbsp;A&nbsp;&nbsp;C&nbsp;D&nbsp;&nbsp; A&nbsp;Some Text &nbsp; here", // original

"&nbsp;AA&nbsp;A&nbsp;&nbsp;C&nbsp;D&nbsp;&nbsp; A &nbsp;Some Text &nbsp; here" // space before/after

};

foreach (string input in inputs)
{
    string result = Regex.Replace(input, pattern, "#");
    Console.WriteLine("Original: {0}\nResult: {1}", input, result);
}

Output:

Original: &nbsp;AA&nbsp;A&nbsp;&nbsp;C&nbsp;D&nbsp;&nbsp; A&nbsp;Some Text &nbsp; here

Result: &nbsp;AA#A&nbsp;&nbsp;C#D&nbsp;&nbsp; A#Some Text &nbsp; here

Original: &nbsp;AA&nbsp;A&nbsp;&nbsp;C&nbsp;D&nbsp;&nbsp; A &nbsp;Some Text &nbsp; here

Result: &nbsp;AA#A&nbsp;&nbsp;C#D&nbsp;&nbsp; A &nbsp;Some Text &nbsp; here

Ahmad Mageed
Thank's a lot. Next time I'll simple send you my sources to fix :)Excellent example!!!
ManniAT