As the title says, I need a Regex to check if a string has this four words (Update, Rollback, Skip, Not Now) and only return them if all of them are present, if not it doesn’t return anything.
Here is an example:
{"Update":"iVBORw0KGgo","Rollback":"iVBORw0KGgo","Skip":"iVBORw0KGgo","Not Now":"iVBORw0KGgo"}
In this case, it should return [Update, Rollback, Skip, Not Now]
{"Update":"iVBORw0KGgo","Skip":"iVBORw0KGgo","Not Now":"iVBORw0KGgo"}
In this case, it shouldn’t return any value
I tried to create one by myself but my knowledge of Regex is very basic:
(Update|Rollback|Skip|Not Now)
Thanks in advance!
CodePudding user response:
As an alternative to regex, you can use JSON.parse
to parse the string into an object and Object.keys
to get the properties:
const str = `{"Update":"iVBORw0KGgo","Rollback":"iVBORw0KGgo","Skip":"iVBORw0KGgo","Not Now":"iVBORw0KGgo"}`;
const keys = Object.keys(JSON.parse(str))
const result = keys.sort().toString() == "Not Now,Rollback,Skip,Update" ? keys : "";
console.log(result)
CodePudding user response:
While regex is clearly not a good tool for the job, you can do something like this:
re.match("(?=.*Update.*)(?=.*Skip.*)",string)
"(?=WORD)"
matches if the expression follows, but doesn't consume any of the string.
Of course, complete the regex by all 4 words that you want similarly.
Also notice that regex by itself doesn't return anything. You need to code for this.
CodePudding user response:
Use this:
^(?=.*Update)(?=.*Rollback)(?=.*Skip)(?=.*Not Now).*$
(?=...)
means that if you lookahead, you find this pattern.
So if we find all these 4 pattern, we accept the result.