简体   繁体   English

将正则表达式从ruby转换为PHP

[英]Converting regex from ruby to PHP

I have been trying to convert a regular expression from ruby to PHP, however I have had little luck. 我一直在尝试将正则表达式从ruby转换为PHP,但是我没有运气。

This is the ruby regular expression: 这是ruby正则表达式:

QUOTED_LITERAL = /"[^"\\]*(?:\\.[^"\\]*)*"/
UNQUOTED_LITERAL = /[^\s=,][^\s=,\\]*(?:\\.[^\s=,\\]*|=[^,>])*/
LITERAL = /(#{QUOTED_LITERAL}|#{UNQUOTED_LITERAL})/
PAIR = /#{LITERAL}\s*=>\s*#{LITERAL}/

And this is my go in PHP: 这是我的PHP:

 const PAIR = '/("[^"\\]*(?:\\.[^"\\]*)*"|[^\s=,][^\s=,\\]*(?:\\.[^\s=,\\]*|=[^,>])*)\s*=>\s*("[^"\\]*(?:\\.[^"\\]*)*"|[^\s=,][^\s=,\\]*(?:\\.[^\s=,\\]*|=[^,>])*)/';

However when I run 但是,当我跑

$result = preg_match_all(self::PAIR, $input, $matches);

I get the error: 我收到错误:

preg_match_all(): Compilation failed: unmatched parentheses at offset 62


However when run it through, http://www.phpliveregex.com/ with the test data: 但是,当运行它时, http//www.phpliveregex.com/与测试数据:

"foo" => "bar", "foo" => bar, foo => "bar"

it seems to work fine. 它似乎工作正常。

Not sure whats going on. 不知道最近发生了什么。

The problem lies with your backslashes. 问题出在你的反斜杠上。

I managed to get it to compile after removing all backslashes. 删除所有反斜杠后,我设法让它编译。

Then, I replaced all double slashes with 4 of them, and preg_match_all() was able to compile the regex too. 然后,我用4个替换了所有双斜杠,并且preg_match_all()也能够编译正则表达式。

const PAIR = '/("[^"\\\\]*(?:\\\\.[^"\\\\]*)*"|[^\s=,][^\s=,\\\\]*(?:\\\\.[^\s=,\\\\]*|=[^,>])*)\s*=>\s*("[^"\\\\]*(?:\\\\.[^"\\\\]*)*"|[^\s=,][^\s=,\\\\]*(?:\\\\.[^\s=,\\\\]*|=[^,>])*)/';

You might have to edit it to get the exact regex you want. 您可能需要编辑它以获得所需的确切正则表达式。 You had the compilation error because \\\\ was fed to the regex engine as \\ , which escaped the immediate square brackets. 你有编译错误,因为\\\\被送到正则表达式引擎作为\\ ,它转义了直接的方括号。 To encode a literal backslash, you need to use \\\\\\\\ - once for the string, and once for the regex engine. 要编码文字反斜杠,您需要使用\\\\\\\\ - 一次用于字符串,一次用于正则表达式引擎。

string '\\\\'  --becomes--> regex \\ --becomes--> literal \

Ruby doesn't have this problem because its regex syntax is separate from its string syntax. Ruby没有这个问题,因为它的正则表达式语法与其字符串语法是分开的。

(Related question: preg_match(): Compilation failed: unmatched parentheses .) (相关问题: preg_match():编译失败:括号不匹配 。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM