使用正则表达式检查逗号的用法

Ale*_*lex 6 php regex

如何编写一个正则表达式,在字符串中发现错误的逗号用法,即:1.对于非数字,之前没有空格,之后有1个空格; 2.对于数字,如果前面有1-3位数字,后跟3位数字,则允许使用逗号.

一些测试用例:

  • 你好,世界
  • 你好,世界=>不对
  • 你好,世界=>不对
  • 1,234个世界
  • 1,23个世界=>不正确
  • 1,2345世界=>不正确
  • 你好,123个世界=>不正确
  • 你好,1234,567世界=>不正确
  • 你好,12,34,567个世界=>不正确
  • (新的测试用例)你好1,2和3个世界
  • (新的测试用例)你好$ 1,234世界
  • (新的测试用例)你好$ 1,2345世界=>不正确
  • (新测试案例)你好"1,234"世界
  • (新的测试用例)你好"1,23"世界=>不正确

因此我认为我有一个正则表达式来捕获语法错误的单词(?![\S\D],[\S\D])(捕获非空格/数字后面跟着非空格/数字的逗号),并将其与另一个正则表达式连接以捕获数字不良语法,通过(?!(.?^(?:\d+|\d{1,3}(?:,\d{3}))(?:.\d+).把它放在一起得到了我

preg_match_all("/(?![\S\D],[\S\D])|(?!(.*?^(?:\d+|\d{1,3}(?:,\d{3})*)(?:\.\d+)?$))/",$str,$syntax_result);

..但显然它不起作用.应该怎么做?

================编辑================

感谢Casimir et Hippolyte的回答,我得到了它的工作!我已经更新了他的答案,以处理更多的角落案件.Idk如果我添加的语法是最有效的,但它现在可以工作.我会更新这个,因为更多的角落案件出现了!

$pattern = <<<'LOD'
~
(?: # this group contains allowed commas
    [\w\)]+,((?=[ ][\w\s\(\"]+)|(?=[\s]+))  # comma between words or line break
  |
    (?<=^|[^\PP,]|[£$\s]) [0-9]{1,3}(?:,[0-9]{3})* (?=[€\s]|[^\PP,]|$) # thousands separator
) (*SKIP) (*FAIL) # make the pattern fail and forbid backtracking
| , # other commas
~mx
LOD;
Run Code Online (Sandbox Code Playgroud)

Cas*_*yte 3

它不防水,但这可以让您了解如何继续:

\n\n
$pattern = <<<\'LOD\'\n~\n(?: # this group contains allowed commas\n    \\w+,(?=[ ]\\w+)  # comma between words\n  |\n    (?<=^|[^\\PP,]|[\xc2\xa3$\\s]) [0-9]{1,3}(?:,[0-9]{3})* (?=[\xe2\x82\xac\\s]|[^\\PP,]|$) # thousands separator\n) (*SKIP) (*FAIL) # make the pattern fail and forbid backtracking\n| , # other commas\n~mx\nLOD;\n\npreg_match_all($pattern, $text, $matches, PREG_OFFSET_CAPTURE);\n\nprint_r($matches[0]);\n
Run Code Online (Sandbox Code Playgroud)\n\n

这个想法是从匹配结果中排除允许的逗号,以仅获得不正确的逗号。第一个非捕获组包含一种用于正确情况的黑名单。(您可以轻松添加其他案例)。

\n\n

[^\\PP,]表示“除”之外的所有标点符号,,但您可以用更明确的允许字符列表替换此字符类,例如:[("\']

\n\n

您可以在此处此处找到有关(*SKIP)和的更多信息(*FAIL) 的更多信息。

\n