preg_match(): 编译失败:在偏移量 2 处没有重复的内容


preg_match(): Compilation failed: nothing to repeat at offset 2

我不知道为什么我的正则表达式会中断。

我希望它匹配:

$100,000

100,000

100000(我知道它与此不匹配,但我希望它匹配)

preg_match("/^'$?(?!0.00)'d{1,3}(,'d{3})*('.'d'd)?$/", $string);

那么我怎样才能让它也匹配最后一个,为什么我会收到此错误?这个正则表达式在我的 JavaScript 检查中工作正常。

谢谢

您需要转义反斜杠才能使其成为文字,因为它作为 PHP 字符串语法的一部分转义了美元符号。

preg_match("/^'''$?(?!0.00)'d{1,3}(,'d{3})*('.'d'd)?$/", $string);

或使用单引号而不是双引号:

preg_match('/^'$?(?!0.00)'d{1,3}(,'d{3})*('.'d'd)?$/', $string);

要允许不带逗号的数字,您可以使用交替:

preg_match('/^'$?(?!0.00)('d{1,3}(,'d{3})*|'d+)('.'d'd)?$/', $string);

添加两个斜杠

preg_match("/^'''$?(?!0.00)'d{1,3}(,'d{3})*('.'d'd)?$/", $string,$matches);
               ^^

代码

<?php
$string='$100,000';
preg_match("/^'''$?(?!0.00)'d{1,3}(,'d{3})*('.'d'd)?$/", $string,$matches);
print_r($matches);

OUTPUT :

Array
(
    [0] => $100,000
    [1] => ,000
)

更新:如果要匹配11000等数字,请使用下面的一个,并注意更改:

preg_match("/^'''$?(?!0.00)'d{1,3}(',?'d{3})*('.'d'd)?$/", $string,$matches);
                                     ^ here making the comma optional