转义正则表达式以获得有效的 JSON
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17597238/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Escaping Regex to get Valid JSON
提问by goldisfine
In my schema, I want to recognize certain patterns to restrict the type of data that a user can enter. I use regex to restrict what a user can enter, but the regex get flagged when I try to validate the JSON using an online validator like this one.
在我的架构中,我想识别某些模式来限制用户可以输入的数据类型。我用正则表达式来限制哪些用户可以进入,但正则表达式GET标记,当我尝试使用在线验证这样来验证JSON一个。
Is there a way to make the validator ignore the regex special chars that are disagreeing with it, but still keep the regex?
有没有办法让验证器忽略不同意它的正则表达式特殊字符,但仍然保留正则表达式?
The weird thing is that the validator only trips up on certain instances. For instance, it flags the second and not the first instance of regex despite them being identical here:
奇怪的是,验证器只会在某些情况下出错。例如,它标记了正则表达式的第二个而不是第一个实例,尽管它们在这里是相同的:
"institutionname": {
"type": "string",
"description": "institution name",
"label": "name",
"input-type": "text",
"pattern": "^[A-Za-z0-9\s]+$"
},
"bio": {
"type": "string",
"label": "bio",
"input-type": "text",
"pattern": "^[A-Za-z0-9\s]+$",
"help-box": "tell us about yourself"
},
回答by Legion
Its just the slashes that are messing up the validation you could encode them using %5Cwhich is the hex encoding of \or what Mike W says you could double escape like \\and then you could just decode them when you want to use them
它只是被搞乱了,你可以使用这些编码验证斜线%5C这是十六进制编码\或迈克W¯¯说,你可能会增加一倍逃生像\\,然后当你要使用它们你可以只对它们进行解码
回答by kushalvm
The accepted answer doesn't work for me. %5Cdoesn't work well with a linter. Plus manually doing it is a job. How about a very long regex -
接受的答案对我不起作用。%5C不能很好地使用 linter。加上手动完成它是一项工作。一个很长的正则表达式怎么样 -
^(([^<>()[\\]\\.,;:\\s@\"]+(\\.[^<>()[\]\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$
^(([^<>()[\\]\\.,;:\\s@\"]+(\\.[^<>()[\]\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$
So, please don't kill yourself and head to this get this done - https://www.freeformatter.com/json-escape.html#ad-output
所以,请不要自杀,然后去做这件事 - https://www.freeformatter.com/json-escape.html#ad-output
In case the link doesn't work in future, please find some other online tool :)
如果以后链接失效,请找一些其他的在线工具:)

