Skip to main content
 首页 » 编程设计

Php 和 python 正则表达式的区别

2024年08月12日41think

我需要解析一个字符串 'Open URN: 100000 LA: '并从中得到 100000。 在 python 正则表达式上 (?<=Open URN: )[0-9]+(?= LA:)工作正常但在 php 中它给出以下错误:

preg_match(): Unknown modifier '[' 

我需要它在 php 上运行,所以请帮我解决这个问题并告诉我 python 和 php 正则表达式的区别。

请您参考如下方法:

你必须使用 delimiters当你使用 Perl Compatible Regular Expressions (PCRE) functions 时在 PHP 中( preg_match() 属于)。

来自documentation :

When using the PCRE functions, it is required that the pattern is enclosed by delimiters. A delimiter can be any non-alphanumeric, non-backslash, non-whitespace character.

使用分隔符的原因是您可以添加pattern modifiers在最后一个定界符之后,例如进行不区分大小写的匹配:

#[a-z]#i  // # is the delimiter. 

回到你的问题:

在你的例子中,PHP 认为括号 ()是你的分隔符(是的,左括号和右括号是有效的分隔符,请参阅 documentation )和 ?<=Open URN:是你的模式。然后遇到[并将其视为 pattern modifier , 但它不是有效的。

带分隔符的模式 % :

preg_match('%(?<=Open URN: )[0-9]+(?= LA:)%', 'Open URN: 100000 LA: '); 

documentation of preg_match() 中有很多例子


Python 与 PHP

关于 Python 中的正则表达式,我唯一发现的是 Perl syntax is used但我不知道是否支持完整的语法。
如前所述,PHP 使用 PCRE。 Description of the differences between PCRE and Perl regex.