REGEX使用任何单个字符的JSON样式字符串
需要验证的字符串采用以下格式,并非严格意义上的JSON,并且无法使用PHP的JSON编码过程进行验证。 请注意,键中的%%是必需的。
// As a single pair
{"%%key%%":"value"}
// Or comma delimited pairs
{"%%key%%":"value","%%key 2%%":"value 2", ...etc...}
目前的REGEX已成功验证上述内容:
{"%%[a-zA-Z0-9]+%%":"[a-zA-Z0-9 ]+"(?:,"%%[a-zA-Z0-9]+%%":"[a-zA-Z0-9 ]+")*}
有效示例:https://regex101.com/r/4y1uEu/1
无效示例(第二个值没有引号):https://regex101.com/r/4y1uEu/2
值需要支持额外的字符,理想情况下,任何字符,所以我改变了REGEX
{"%%[a-zA-Z0-9]+%%":".+"(?:,"%%[a-zA-Z0-9]+%%":".+")*}
与此字符串匹配的字符串与所需的模式不匹配:
{"%%hello%%":"world","%%foo%%":bar"}
^ missing quote
误报示例:https://regex101.com/r/4y1uEu/3
我认为原因在于整个部分使用了新的“任何字符” : {“%% hello %%”:“ world”,“%% foo %%”:bar “}
我怎样才能让“任何角色”匹配结束? 这种方法注定失败,因为报价本身就是“任何角色”?
预期结果的一些例子:
{"%%hello%%":"world","%%foo%%":"bar"}
有效
{"%%hello%%":"world lorem","%%foo%%":"bar ipsum"}
有效
{"%%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/92707.html