1

I want to remove all html tags from a string.i can achieve this using REGX.

but inside the string if it contains number inside the angular braces <100> it should not remove it .

         var withHtml = "<p>hello <b>there<1234></b></p>";
        var withoutHtml = Regex.Replace(withHtml, "\\<[^\\>]*\\>", string.Empty); 

Result: hello there

but needed output : hello there 1234

4
  • 2
    <1234> is not an html tag... Commented Aug 29, 2013 at 9:43
  • yes .but the REGX removes <1234> also because its inside the brackects.I want the number also to display Commented Aug 29, 2013 at 9:46
  • Regex don't know which is Valid HTML and which is not. So regex is not the way to do it. Consider using HTMlAgilityPack Commented Aug 29, 2013 at 9:48
  • Correct HTML would have those two angle brackets around the number escaped/encoded as &lt; and &gt;. Commented Aug 29, 2013 at 10:25

2 Answers 2

1

Your example of HTML isn't valid HTML since it contains a non-HTML tag. I figure you intended for the angle-brackets to be encoded.

I don't think regular expressions are suitable for HTML parsing. I recommend using an HTML parser such as HTML Agility Pack to do this.

Here's an example:

var withHtml = "<p>hello <b>there&lt;1234&gt;</b></p>";
var document = new HtmlDocument();
document.LoadHtml(withHtml);

var withoutHtml = HtmlEntity.DeEntitize(document.DocumentNode.InnerText);

Just add the HtmlAgilityPack NuGet package and a reference to System.Xml to make it work.

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

Comments

0

Not sure you can do this in one regular expression, or that a regex is really the correct way as others have suggested. A simple improvement that gets you almost there is:

Regex.Replace(withHtml, "\\<[^\\>0-9]*\\>", string.Empty);

Gives "hello there<1234>" You then just need to replace all angled brackets.

1 Comment

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.