aishlin
aishlin

Reputation: 1

Regexp matching html tag

I have following regex:

^(?:(?!<(\w+)(\s+(\w+)\s*\=\s*(\'|")(.*?)\\4\s*)*\s*>).)*$

And I have textbox where user can type JavaScript code so regex should match things like:

if ( i < html > 0 ) || ( j > 10 )

and it works but only for single line but it must work for multiline

btw. I test regex on this page: http://www.zytrax.com/tech/web/regex.htm#experiment

Upvotes: 0

Views: 198

Answers (3)

Alan Moore
Alan Moore

Reputation: 75252

The reason it fails on multiline input is because the dot (.) doesn't match newline characters by default. You can fix it by adding (?s) to the front of the regex to put it in Singleline mode (also known as DOTALL mode in some flavors, because it empowers the dot to match everything including newlines).

Multiline mode, which was mentioned by other responders, is probably not relevant to your case. What it does is allow the ^ and $ anchors to match the beginning and end of individual lines as well as the beginning and end of the whole string.

You said you were using this in an ASP.NET RegularExpressionValidator, which brings up another potential problem. If the validator is set up to do validations on the client side as well as the server, it will be the JavaScript regex flavor doing the work, not .NET. JavaScript doesn't support Singleline/DOTALL mode, so you need to replace the dot in your regex with something else that matches all characters; most people use [\s\S] (any whitespace character or any character that's not whitespace).

Here's the resulting regex, including a more robust idiom for the quoted attribute values:

^(?:(?!<\w+(?:\s+\w+\s*\=\s*(['"])(?:(?!\1).)*\1)*\s*>)[\s\S])*$

Upvotes: 1

David Brabant
David Brabant

Reputation: 43559

All regex engine have an option for matching multi-line. Since your question doesn't mention which engine you are using, it's not easy to help you further then that.

Upvotes: 0

Joanna Derks
Joanna Derks

Reputation: 4063

If it's javaScript you'll the m multiline modifier in your regex:

you can test that it works here: http://regexpal.com/

Upvotes: 0

Related Questions