0

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

5 Answers 5

2

This should cover all 3 of your requirements. Excuse the formatting; I had to back-tick the first few lines for the   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

Sign up to request clarification or add additional context in comments.

1 Comment

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

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.

1 Comment

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

You should try the following example :

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

3 Comments

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

http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.replace.aspx

Comments

0

You may use this one

[^^\s(nbsp;)](nbsp;)[^$\s(nbsp;)]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.