I want to come up with Regular Expression to return true if the a
closed html tag is matched with an open one in specific text that gets passed in
JavaScript. If there is an unmatched tag, it should return
false;
For example, if the following text is I can only get it to match the first div How can I fix it The In order to fix href="https://www.debuggex.com/i/6gy-t3B7subnWrvp.png" href="http://jsfiddle.net/r2LsN/" The then
passed "
it should return true
but if the following text gets passed
"
false
tags to return true with the following
expression var text =
"
var text2 =
"
var regex =
/[^<>]*<(\w+)(?:(?:\s+\w+(?:\s*=\s*(?:".*?"|'.*?'|[^'">\s]+))?)+\s*|\s*)>[^<>]*<\/\1+\s*>[^<>]*|[^<>]*<\w+(?:(?:\s+\w+(?:\s*=\s*(?:".*?"|'.*?'|[^'">\s]+))?)+\s*|\s*)\/>[^<>]*||^[^<>]+$/;
var match = regex.test(text);
console.log(match); // true
var
match = regex.test(text2);
console.log(match2); // still true should be
false
so it functions the way I want it to.
test
method returns true for match2
because it has
found a match.
it, change your regex this way:^(?:<(\w+)(?:(?:\s+\w+(?:\s*=\s*(?:".*?"|'.*?'|[^'">\s]+))?)+\s*|\s*)>[^<>]*<\/\1+\s*>|<\w+(?:(?:\s+\w+(?:\s*=\s*(?:".*?"|'.*?'|[^'">\s]+))?)+\s*|\s*)\/>||[^<>]+)*$
Description
(click to enlarge)
rel="nofollow">
src="https://www.debuggex.com/i/6gy-t3B7subnWrvp.png" alt="Regular expression
visualization">Demo
rel="nofollow">http://jsfiddle.net/r2LsN/Discussion
regex defines all the allowed patterns
firstly:
with body:
without body:
(here we can find zero or more
spaced before /
)
is not <
or
>
.
these patterns can appear zero or more times between the beginning and the end of the
tested string:
^(?:pattern1|pattern2|pattern3|pattern4)*$
.
No comments:
Post a Comment