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

正则表达式将值拉到方括号之间

  •  1
  • e36M3  · 技术社区  · 15 年前

    “一些东西[234][3243]”

    .*\[(.*)\].* 然而,这只允许我在括号之间提取最后一个值,在本例3243中。如何提取所有值,即在匹配对象中获取更多组。

    5 回复  |  直到 7 年前
        1
  •  3
  •   Seattle Leonard    15 年前
            string s = "something[234][3243]";
            MatchCollection matches = Regex.Matches(s, @"(?<=\[)\d+(?=\])");
            foreach (Match m in matches)
            {
                Console.WriteLine(m.Value);
            }
    

    你可以通过分组parens来做到这一点,但是如果你使用回顾和展望,那么你就不需要把分组从匹配中拉出来。

        2
  •  3
  •   kennytm    15 年前

    如果括号之间只允许数字,则使用

    \[(\d+)\]
    

    the .Matches method 得到 比赛。

    var theString = "something [234][3243]";
    var re = new Regex(@"\[(\d+)\]");
    foreach (Match m in re.Matches(theString)) {
       Console.WriteLine(m.Groups[1].Value);
    }
    

    \[([^]]+)\] 相反。)

        3
  •  1
  •   d7samurai    15 年前

    如果要搜索方括号中的任何字符串,而不仅仅是数字,则 ? )做这个:

    \[(.+?)\]

    然后遍历所有匹配项以命中所有括号内容(包含在捕获组中)。正如其他人所说,如果加上“向前看”和“向后看”,匹配本身将是无括号的。

        4
  •  0
  •   tinifni    15 年前

    \[(.*?)]
    
        5
  •  0
  •   Ruan Mendes    15 年前

    我知道这不是一个JavaScript问题,但这里是如何在JS中实现的,因为我不太懂C。这不使用lookahead或lookbehind,并且匹配括号内的任何内容,而不仅仅是数字

    var reg = /\[(\d+)\]/g;
    var reg = /\[([^\]]+)\]/g;
    var str = "something [234] [dog] [233[dfsfsd6]";
    
    var matches = [];
    var match = null;
    while(match = reg.exec(str)) {
      // exec returns the first match as the second element in the array
      // and the next call to exec will return the next match or null
      // if there are no matches
      matches.push(match[1]);
    }
    
    // matches = [ "234", "dog", "233[dfsfsd6" ]