Jack
Jack

Reputation: 3

How to write regex to replace spaces between span tags with  

I want the space between the span tags to be replaced by  

<span style="font-size:11;color:black"> </span>

I wrote this regex:

Regex.Replace(xml, @"<span[^>]*?>\s*</span>", (match) => match.Value.Replace(" ", "&nbsp;"), RegexOptions.IgnoreCase);

But it give me this output:

<span&nbsp;style="font-size:11;color:black">&nbsp;</span>

It also places the &nbsp; after the span.

Upvotes: 0

Views: 1506

Answers (2)

MarioVW
MarioVW

Reputation: 2534

Use Regex.Replace

Regex regex = new Regex(@"<span([^>]*)>\s*</span>");
String output = regex.Replace(input, "<span$1>&nbsp;</span>");

Upvotes: 0

Jens
Jens

Reputation: 25573

You could use

@"(?<=<span[^>]*?>)\s*(?=</span>)"

as your regex.

Be aware, that parsing HTML with regular expressions is frowned upon and will break horribly when encountering (among others) HTML Comments and JavaScript.

Upvotes: 1

Related Questions