0

I'm looking for a regex to replace whitespaces INTO an XML tag. For exemple:

<TAG 1>bla bla bla</TAG 1>

replace to:

<TAG1>bla bla bla</TAG1>

I wrote this:

string currentLine = Regex.Replace(currentLine,
@"(?<=\</?\S*)\s+(?=\S*\>)", String.Empty);

but it's not working, because it's remove between 2 tag also...

Thank you for your help!

1

1 Answer 1

1

You should bear in mind that \S matches any non-whitespace character, that is why in case some text is glued to < or > you may match spaces outside of angle brackets.

You can use

var result = Regex.Replace(text, @"(?<=<[^<>]*)\s(?=[^<>]*>)", "");

See the regex demo. Details:

  • (?<=<[^<>]*) - a location immediately preceded with < and then any zero or more chars other than < and >
  • \s - a whitespace
  • (?=[^<>]*>) - a location immediately followed with any zero or more chars other than < and > and then a >.
Sign up to request clarification or add additional context in comments.

1 Comment

Good, +1, but it's noteworthy that this assumes that there are no XML attributes.

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.