REGEX a JSON style string using any single character
The string needing validated is in the following format, which is not strictly JSON and cannot be validated using PHP's JSON encoding process. Note the %%'s in the keys are required.
// As a single pair
{"%%key%%":"value"}
// Or comma delimited pairs
{"%%key%%":"value","%%key 2%%":"value 2", ...etc...}
The current REGEX successfully validates for the above:
{"%%[a-zA-Z0-9]+%%":"[a-zA-Z0-9 ]+"(?:,"%%[a-zA-Z0-9]+%%":"[a-zA-Z0-9 ]+")*}
Valid Example: https://regex101.com/r/4y1uEu/1
Invalid Example (no quotes around second value): https://regex101.com/r/4y1uEu/2
Values need to support additional characters, ideally any character, so I changed the REGEX to
{"%%[a-zA-Z0-9]+%%":".+"(?:,"%%[a-zA-Z0-9]+%%":".+")*}
Which matches for this string which does not match the desired pattern:
{"%%hello%%":"world","%%foo%%":bar"}
^ missing quote
Example of false positive: https://regex101.com/r/4y1uEu/3
I believe reason is that the new "any character" is being used for this whole section: {"%%hello%%":" world","%%foo%%":bar "}
How can I somehow make "any character" matching end? Is this method doomed to fail due to a quote itself being "any character"?
Some examples of expected results:
{"%%hello%%":"world","%%foo%%":"bar"}
Valid
{"%%hello%%":"world lorem","%%foo%%":"bar ipsum"}
Valid
{"%%hello%%":"world lo-rem","%%foo%%":"bar ips'um"}
Valid
{"%%hello%%":"world lo-rem","%%foo%%":"lorem "ipsum" dolor"}
Valid
var pattern = /^{("%%[a-zA-Z0-9]+%%":"([A-z0-9s"'-])*"s*(,|})s*)*$/
str = "{"%%hello%%":"world lo-rem","%%foo%%":"lorem "ipsum" dolor"}"
console.log(str+ ' '+pattern.test(str))
str = "{"%%hello%%":"world lo-rem","%%foo%%":"bar ips'um"}"
console.log(str+ ' '+pattern.test(str))
str = "{"%%hello%%":"world","%%foo%%":bar"}"
console.log(str+ ' '+pattern.test(str))
str = "{"%%hello%%":"world","%%foo%%":bar}"
console.log(str+ ' '+pattern.test(str))
链接地址: http://www.djcxy.com/p/92708.html
上一篇: 如何根据预期类型检查数据有效性?