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 passed I can only get it to match the first div tags to return true with the following expression How can I fix it so it functions the way I want it to. Answer The In order to fix it, change your regex this way: The regex defines all the allowed patterns firstly: then these patterns can appear zero or more times between the beginning and the end of the tested string: "
it should return true
but if the following text gets passed "
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
test
method returns true for match2
because it has found a match.^(?:<(\w+)(?:(?:\s+\w+(?:\s*=\s*(?:".*?"|'.*?'|[^'">\s]+))?)+\s*|\s*)>[^<>]*<\/\1+\s*>|<\w+(?:(?:\s+\w+(?:\s*=\s*(?:".*?"|'.*?'|[^'">\s]+))?)+\s*|\s*)\/>||[^<>]+)*$
Description (click to enlarge)
Demo
Discussion
(here we can find zero or more spaced before /
)<
or >
.^(?:pattern1|pattern2|pattern3|pattern4)*$
.
No comments:
Post a Comment