代码之家  ›  专栏  ›  技术社区  ›  pchap10k

用于捕获编号文本列表的正则表达式

  •  1
  • pchap10k  · 技术社区  · 16 年前

    我有一个测试列表,我正试图从使用正则表达式捕获数据。

    以下是文本格式的示例:

    (1) this is a sample string /(2) something strange /(3) another bit of text /(4) the last one/ something!/
    

    /\(?\d\d?\)([^\)]+)(\/|\z)/
    

    不幸的是,有些数据包含如下括号:

    (1) this is a sample string (1998-1999) /(2) something strange (blah) /(3) another bit of text /(4) the last one/ something!/
    

    有人想试试这个吗? 谢谢:D

    3 回复  |  直到 16 年前
        1
  •  1
  •   cletus    16 年前

    我想试试这个:

    \((\d+)\)\s+(.*?)(?=/(?:\(\d+\)|\z))
    

    这个看起来相当吓人的正则表达式执行以下操作:

    • 它寻找一个或多个用括号括起来的数字并捕获它们;
    • 括号中的数字后面必须至少有一个空格字符。忽略此空白(未捕获);
    • 使用非贪婪通配符表达式。这是使用否定字符组(例如 [^/]+
    • 积极的展望( (?=...) )表示表达式后面必须跟一个反斜杠,然后是:
      • 字符串终止符。

    给您一个PHP示例(您不指定您的语言):

    $s = '(1) this is a sample string (1998-1999) /(2) something strange (blah) /(3) another bit of text /(4) the last one/ something!/';
    preg_match_all('!\((\d+)\)\s+(.*?)(?=/(?:\(\d+\)|\z))!', $s, $matches);
    print_r($matches);
    

    输出:

    Array
    (
        [0] => Array
            (
                [0] => (1) this is a sample string (1998-1999) 
                [1] => (2) something strange (blah) 
                [2] => (3) another bit of text 
                [3] => (4) the last one/ something!
            )
    
        [1] => Array
            (
                [0] => 1
                [1] => 2
                [2] => 3
                [3] => 4
            )
    
        [2] => Array
            (
                [0] => this is a sample string (1998-1999) 
                [1] => something strange (blah) 
                [2] => another bit of text 
                [3] => the last one/ something!
            )
    
    )
    

    • 您没有指定要捕获的内容。我已经假定了列表项编号和文本。这可能是错误的,在这种情况下,只要去掉那些括号。无论哪种方法,你都可以得到整场比赛;
    • 我从比赛中去掉了后面的斜杠。这可能不是你的意图。再就是改变捕捉方式;
    • 我允许商品编号有任意位数。你的版本只允许两个。如果你喜欢那样的话,就换掉它 \d+ 具有 \d\d?
        2
  •  1
  •   kennytm    16 年前

    / 在字符串的开头添加 (0) 到字符串的末尾,然后用该模式拆分整个字符串 \/\(\d+\) ,并丢弃第一个和最后一个空元素。

        3
  •  1
  •   Paul Creasey    16 年前

    只要/不能出现在文本中。。。

     \(?\d?\d[^/]+