javascript JSON 中的正则表达式模式?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25426464/
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
Regex pattern in JSON?
提问by Eric
I'm trying to have a single JSON file to validate data both in front (JS) and back (PHP). I cannot figure out how to have my pattern in a json string, PHP won't convert it. Here's what I'd like to use (email validation):
我正在尝试使用一个 JSON 文件来验证前端 (JS) 和后端 (PHP) 的数据。我不知道如何在 json 字符串中包含我的模式,PHP 不会转换它。这是我想使用的(电子邮件验证):
'{"name":"email", "pattern":"^[a-z0-9]+(\.[_a-z0-9]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,15})$"}'
I suppose there's something in pattern that doesn't get treated as a string? This as it is, won't convert to an object in PHP. I shouldn't have to escape anything but I might be wrong...
我想模式中的某些东西不会被视为字符串?这实际上不会转换为 PHP 中的对象。我不应该逃避任何事情,但我可能错了......
thanks
谢谢
Edit: Tried this as suggested in comments:
编辑:按照评论中的建议尝试此操作:
json_decode('{"name":"email", "pattern":"^[a-z0-9]+(\.[_a-z0-9]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,15})$"}??'); ==> NULL
回答by ljacqu
The problem are the backslashes \
. Use two to signal that there is one and it will work well:
问题是反斜杠\
。使用两个来表示有一个,它会运行良好:
{"name":"email","pattern":"^[a-z0-9]+(\.[_a-z0-9]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,15})$"}
The above is valid JSON but will cause trouble as PHP string, because \\
will already be interpreted as one \
before it is passed to json_decode()
, and we're back where we started from. As decezekindly pointed out in the comments, this can be solved by adding four backslashes:
以上是有效的 JSON,但作为 PHP 字符串会引起麻烦,因为在传递给 之前\\
已经被解释为一个,我们又回到了我们开始的地方。正如deceze在评论中友好指出的那样,这可以通过添加四个反斜杠来解决:\
json_decode()
{"name":"email","pattern":"^[a-z0-9]+(\\.[_a-z0-9]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*(\\.[a-z]{2,15})$"}
Or by immediately passing the contents from file_get_contents()
(or similar) to json_decode()
.
或者立即将内容从file_get_contents()
(或类似的)传递到json_decode()
.