简体   繁体   中英

Regex to match pattern only if a string is not present in pattern

Stuck with finding a regex for a typical scenario. Not sure how this can be achieved in regex.

Regex ---> (?is)[^:]\/\/
Payload ---> Regexp,test//check//last://
Matches ---> t// and k//

Issue : I need to modify the above regex to ignore match for // only if the test string starts with "data:image"(as in below payload).

Payload ---> data:image/png;base64,test//check//last://

In this above case it should not match for my criteria (match for //) since the test string starts with "data:image"

Suggest a way to modify the above regex, so that we can handle this case.

If I understood your question correctly, you want the regex to match your pattern // and the preceding character which shouldn't be : . And the matches should only be done if the test string does not start with data:image .

/(?!data:image)(?:.*?)([^:]\/\/)/giy
  • (?!data:image) ensures that the string doesn't start with data:image
  • (?:.*?) non-capturing non-greedy match
  • ([^:]\\/\\/) your match // and the preceding character which shouldn't be :
  • /y to denote a sticky match so that it matches only from where a previous match ended. That way, for strings starting with data:image it won't match anything

 var regex = /(?!data:image)(?:.*?)([^:]\\/\\/)/giy // This shouldn't match since test string starts with data:image var payload = "data:image/png;base64,test//check//last://"; var match = regex.exec(payload); console.log(match); // This should find matches since payload doesn't start with data:image var anotherpayload = "Regexp,test//check//last://"; match = regex.exec(anotherpayload); while (match != null) { // Accessing group 1 console.log(match[1]) match = regex.exec(anotherpayload); } 

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