preg_match():编译失败:缺少终止]对于带有转义的\的字符类

时间:2017-05-25 11:27:26

标签: php json regex compiler-warnings

我正在尝试在JSON字符串上运行正则表达式,以便在继续我的脚本之前验证数据是否符合预期。

以下是运行正则表达式的JSON示例:

option+right/left

我在phpliveregex.com工作时测试了以下正则表达式:

[{"id":"01001001","b":"1","c":"1","v":"1","t":"Some \"Text\""},{"id":"01001002","b":"1","c":"1","v":"2","t":"More Text"},{"id":"01001003","b":"1","c":"1","v":"3","t":"And Even More"}]

以下是我在PHP中将它放在一起的方式:

\[(\{"id":"[0-9]{8}","b":"[0-9]{1,2}","c":"[0-9]{1,2}","v":"[0-9]{1,3}","t":"[^"\\]*(?:\\.[^"\\]*)*"\})(,\{"id":"[0-9]{8}","b":"[0-9]{1,2}","c":"[0-9]{1,2}","v":"[0-9]{1,3}","t":"[^"\\]*(?:\\.[^"\\]*)*"\})*\]

我收到的问题是当我运行此页面时收到此错误

  

警告:preg_match():编译失败:缺少终止] for   偏移202的字符类   第1422行的path_to_file / my-file.php

第1422行是上述代码段的第6行。我相信这指向$sv = '01001001'; $ev = '01001003'; $url = 'http://api.amasterdesigns.com/?sv='.$sv.'&ev='.$ev; $JSON = file_get_contents($url); //return JSON only if properly formatted if(preg_match('/\[(\{"id":"[0-9]{8}","b":"[0-9]{1,2}","c":"[0-9]{1,2}","v":"[0-9]{1,3}","t":"[^"\\]*(?:\\.[^"\\]*)*"\})(,\{"id":"[0-9]{8}","b":"[0-9]{1,2}","c":"[0-9]{1,2}","v":"[0-9]{1,3}","t":"[^"\\]*(?:\\.[^"\\]*)*"\})*\]/',$JSON)){ return json_decode($JSON); } else { return; } 接近我的正则表达式的结尾,但我确实在转义[^"\\]之后终止]

您可以使用PHP sandbox

查看错误

3 个答案:

答案 0 :(得分:1)

这部分:

[^"\\]

需要:

[^"\\\\]

您需要再次加倍反斜杠,因为它们在字符串和正则表达式语法中都充当转义。当\\发送到\时,preg_match会变为],而<div className="search-container"> <AutoComplete className="global-search" size="large" dropdownClassName="certain-category-search-dropdown" dropdownMatchSelectWidth={false} dropdownStyle={{ width: 300, top: 47 }} dataSource={options} onSelect={()=>{this.value = value | ''}} onSearch={this.inputValueChange} placeholder={formatMessage(messages.searchPlaceHolder)} optionLabelProp="" filterOption={false} > <Input suffix={( <Button className="search-btn" size="large" type="primary"> <Icon type="search" /> </Button> )} /> </AutoComplete> </div> 会转义{{1}}而不是将反斜杠视为字符集中的某个字符。

答案 1 :(得分:0)

v的第一次检查错过了一个开头[

"v":"0-9]{1,3}"  // should be:
"v":"[0-9]{1,3}"

答案 2 :(得分:0)

添加@ Barmar的答案,或以nowdoc格式包装你的正则表达式:

$re = <<< 'RE'
/\[(\{"id":"[0-9]{8}","b":"[0-9]{1,2}","c":"[0-9]{1,2}","v":"[0-9]{1,3}","t":"[^"\\]*(?:\\.[^"\\]*)*"\})(,\{"id":"[0-9]{8}","b":"[0-9]{1,2}","c":"[0-9]{1,2}","v":"[0-9]{1,3}","t":"[^"\\]*(?:\\.[^"\\]*)*"\})*\]/
RE;

if (preg_match($re, $JSON)) {
    print_r(json_decode($JSON));
}