RegEx matching HTML tags and extracting text


Question

I have a string of test like this:

<customtag>hey</customtag>

I want to use a RegEx to modify the text between the "customtag" tags so that it might look like this:

<customtag>hey, this is changed!</customtag>

I know that I can use a MatchEvaluator to modify the text, but I'm unsure of the proper RegEx syntax to use. Any help would be much appreciated.

1
7
11/18/2008 8:01:54 PM

Accepted Answer

I wouldn't use regex either for this, but if you must this expression should work: <customtag>(.+?)</customtag>

15
11/18/2008 8:10:19 PM

I'd chew my own leg off before using a regular expression to parse and alter HTML.

Use XSL or DOM.


Two comments have asked me to clarify. The regular expression substitution works in the specific case in the OP's question, but in general regular expressions are not a good solution. Regular expressions can match regular languages, i.e. a sequence of input which can be accepted by a finite state machine. HTML can contain nested tags to any arbitrary depth, so it's not a regular language.

What does this have to do with the question? Using a regular expression for the OP's question as it is written works, but what if the content between the <customtag> tags contains other tags? What if a literal < character occurs in the text? It has been 11 months since Jon Tackabury asked the question, and I'd guess that in that time, the complexity of his problem may have increased.

Regular expressions are great tools and I do use them all the time. But using them in lieu of a real parser for input that needs one is going to work in only very simple cases. It's practically inevitable that these cases grow beyond what regular expressions can handle. When that happens, you'll be tempted to write a more complex regular expression, but these quickly become very laborious to develop and debug. Be ready to scrap the regular expression solution when the parsing requirements expand.

XSL and DOM are two standard technologies designed to work with XML or XHTML markup. Both technologies know how to parse structured markup files, keep track of nested tags, and allow you to transform tags attributes or content.

Here are a couple of articles on how to use XSL with C#:

Here are a couple of articles on how to use DOM with C#:

Here's a .NET library that assists DOM and XSL operations on HTML:


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon