简体   繁体   中英

regex to match subexpression at end of string

I'm trying to test whether the ending pattern in a string is an html closing tag (assuming trailing spaces are trimmed).

var str1 = "<em>I</em> am <strong>dummy</strong> <em>text.</em>"; //ends with html close tag
var str2 = "<em>I</em> am <strong>dummy</strong> <strong>text.</strong>"; //ends with html close tag
var str3 = "<em>I</em> am <strong>dummy</strong> text"; //does not end with html close tag

Using str1 above, I would like to get the position of the ending tag, which is an. Here are my attempts:

var rgx1 = /(<\/em>)$/g; // works. basic scenario. matches closing </em> tags at the end of the string.
var rgx2 = /<\s*\/\s*\w\s*.*?>/g; //matches html closing tags.
var rgx3 = /<\s*\/\s*\w\s*.*?>$/g; //doesn't work. supposed to match closing html tag at the end of the string

console.log(str.search(rgx1))

While rgx1 correctly returns the position of the ending tag, and rgx2 correctly returns the position of a closing html tag in general, I'm trying get a generalized regex that will return the positing of any html tag that ends the string. Why doesn't rgx3 work?

Should just use a negative char class to match anything that's not a closing >

var rgx = /<\/[^>]+>$/g;

as to why rgx3 didn't work... your pattern isn't really good but it should technically match... if it didn't work with the $ on the end there, then the string you are matching probably isn't trimmed as you suppose it to be (or some other thing on the end other than closing html tag)

Seems like there might be an issue with rgx2 and rgx3 - an extra.*? before the > and a missing * after \w - here's how I would write the regexes. The fact that rgx2 was working at all was because of the match all (.*)

var rgx2 = /<\s*\/\s*\w*\s*>/g;
var rgx3 = /<\s*\/\s*\w*\s*>$/g;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM