代码之家  ›  专栏  ›  技术社区  ›  Arron S

regex帮助,如何使表达式的顺序无关紧要?

  •  2
  • Arron S  · 技术社区  · 16 年前

    我不知道如何获得输入字符串参数(价格、商家、类别)的顺序对regex来说无关紧要。我的regex匹配字符串的各个部分,但不匹配整个字符串。我需要能够在其中添加\a\z。

    Pattern: 
     (,?price:(;?(((\d+(\.\d+)?)|min)-((\d+(\.\d+)?)|max))|\d+)+){0,1}(,?merchant:\d+){0,1}(,?category:\d+){0,1}
    
    Sample Strings:
    
    price:1.00-max;3-12;23.34-12.19,category:3
    
    merchant:25,price:1.00-max;3-12;23.34-12.19,category:3
    
    price:1.00-max;3-12;23.34-12.19,category:3,merchant:25
    
    category:3,price:1.00-max;3-12;23.34-12.19,merchant:25
    

    注: 我要补充一点 ?: 在我开始工作后给我所有的小组。

    4 回复  |  直到 16 年前
        1
  •  2
  •   cletus    16 年前

    您有三种选择:

    1. 你可以列举所有可能的顺序。对于3个变量,有6种可能性。很明显,这不具有规模;
    2. 您可以接受可能的副本;或者
    3. 您可以分解字符串,然后分析它。

    (2)指类似于:

    /(\b(price|category|merchant)=(...).*?)*/
    

    您在这里面临的真正问题是,您试图用正则表达式解析本质上是非正则语言的内容。正则表达式描述了一个DFM(确定性有限状态机)或DFA(确定性有限自动机)。正则语言没有状态的概念,因此表达式无法“记住”已有的内容。

    要做到这一点,您必须添加一个“内存”,通常是以堆栈的形式,它生成一个PDA(下推自动机)。

    当人们试图用正则表达式解析HTML,并陷入标签嵌套问题和类似问题时,他们面临的问题是完全相同的。

    基本上,您接受一些边缘条件(比如重复的值),用逗号拆分字符串,然后解析,或者您只是在使用错误的工具来执行该任务。

        2
  •  3
  •   Matchu    16 年前

    您可能应该只通过普通解析来解析这个字符串。用逗号分开,然后用冒号把每一块都分成两块。如果要分别检查每个输入,可以存储验证regex。

    如果你通过regex来做,你可能会说“这个组合或者这个组合或者这个组合”,这会伤害到真正的坏。

        3
  •  0
  •   Anon.    16 年前

    你不试着和一个CThulHugex一起做怎么样?

    /price:([^,]*)/
    /merchant:([^,]*)/
    /category:([^,]*)/
    
        4
  •  0
  •   ghostdog74    16 年前
    $string=<<<EOF
    price:1.00-max;3-12;23.34-12.19,category:3
    
    merchant:25,price:1.00-max;3-12;23.34-12.19,category:3
    
    price:1.00-max;3-12;23.34-12.19,category:3,merchant:25
    
    category:3,price:1.00-max;3-12;23.34-12.19,merchant:25
    EOF;
    
    $s = preg_replace("/\n+/",",",$string);
    $s = explode(",",$s);
    print_r($s);
    

    输出

    $ php test.php
    Array
    (
        [0] => price:1.00-max;3-12;23.34-12.19
        [1] => category:3
        [2] => merchant:25
        [3] => price:1.00-max;3-12;23.34-12.19
        [4] => category:3
        [5] => price:1.00-max;3-12;23.34-12.19
        [6] => category:3
        [7] => merchant:25
        [8] => category:3
        [9] => price:1.00-max;3-12;23.34-12.19
        [10] => merchant:25
    )