I'm trying to come up with a regular expression that will be applied for potentially hundreds of files, as a find..replace in notepad++. It's going to be like an if..else.
Here's what I want to do but as a regex:
if title tag exists and <meta http-equiv="X-UA-Compatible" content="IE=edge" />
does not exist on the page, AND an iframe tag exists, then insert <meta http-equiv="X-UA-Compatible" content="IE=edge" />
right after the title tag.
Sample text:
<title>Some Title</title>
<meta name="description" content="Mydescription." />
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
...
<iframe src="iframeresource"></iframe>
Regex I have thus far:
(<title>.*<\s*\/title>).*?(?!<meta http-equiv="X-UA-Compatible" content="IE=edge"\s*\/>.*?<iframe)
It uses a negative lookahead. I need something like a conditional negative lookahead but the ability to perform substitution, if and only if <meta http-equiv="X-UA-Compatible" content="IE=edge />
does not exist already. I'm not quite sure how to do this with straight regex.
Any ideas would be most appreciated. Thank you.
HTML parsing is best done with a dedicated DOM parser. A regex can only be used to fix a well-structured, consistent HTML code.
If this is the case, use
(?si)\A(?!.*?<meta\s+http-equiv="X-UA-Compatible"\s+content="IE=edge"\s*/>)(.*?<title>.*?</title>)(.*)
and replace with $1\\n<meta http-equiv="X-UA-Compatible" content="IE=edge" />$2\\n
.
(?si)
enables .
to match linebreaks and makes the pattern case insensitive. \\A
matches the start of a file. The (?!.*?<meta\\s+http-equiv="X-UA-Compatible"\\s+content="IE=edge"\\s*/>)
fails the match if the meta tag pattern is matched. (.*?<title>.*?</title>)
consumes and captures text up to and including the first title
tag. Then (.*)
matches the rest of the document.
See the regex demo
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.