简体   繁体   中英

Regex match string if not

I'm using regex to replace image source urls in an html file.

I want for example to replace img/ with <?= $folder ?>/img/

The issue: When I run the regex multiple times it will replace img/ again, creating:

<?= $folder ?>/<?= $folder ?>/img

..and so on. Is there a way to tell regex to replace img/ if not already <?= $folder ?>/img ?

I am trying /^(?:(?!<?= $folder ?>/img).)*$/ but not sure how to first match and check if that it doesn't already contain <?= $folder ?>/img

If you prefer regex, please try:

 function matchIfNot(str) { var newstr = str.replace(/^(?!(<\\?=\\s\\$folder\\s\\?>\\/))(img\\/)/g, "<?= $folder ?>/img/") alert("Old string: " + str + "\\nNew string: " + newstr) } matchIfNot("<?= $folder ?>/img/") matchIfNot("img/") 

Output:

Old string: <?= $folder ?>/img/
New string: <?= $folder ?>/img/

Old string: img/
New string: <?= $folder ?>/img/

Try /(?!<\\?= $folder \\?>)img\\// .

The bit at the beginning there, the (?!< ... ) is the notation for negative look-behind, that is, for checking if ... is earlier in the string. In this case, we're checking if the string
<\\?= $folder \\?> (note the escaped question marks) is earlier in the string. If that section is found earlier in a line with img/ , it will be rejected, and won't match. So, each case of img/ will only be matched once.

This regex will fail for lines with more than one occurence of img/ . There might be a way to allow for multiple occurences, but it would likely be a very long regex; and in my opinion, usually when a regex gets too long, it might be time to switch to a different tool.

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