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

在javascript中进行匹配?

  •  65
  • hsz  · 技术社区  · 14 年前

    有可能在 JavaScript 做一些像 preg_match 确实在 PHP ?

    我希望能从字符串中得到两个数字:

    var text = 'price[5][68]';
    

    分为两个独立变量:

    var productId = 5;
    var shopId    = 68;
    

    编辑: 我也用 MooTools 如果有帮助的话。

    5 回复  |  直到 7 年前
        1
  •  96
  •   Fleshgrinder    9 年前

    javascript有一个 RegExp 对象,它执行您想要的操作。这个 String 对象具有 match() 有助于你摆脱困境的功能。

    var matches = text.match(/price\[(\d+)\]\[(\d+)\]/);
    
        2
  •  28
  •   kander    7 年前
    var text = 'price[5][68]';
    var regex = /price\[(\d+)\]\[(\d+)\]/gi;
    match = regex.exec(text);
    

    match[1]和match[2]将包含您要查找的数字。

        3
  •  18
  •   Tracey Turn    12 年前
    var thisRegex = new RegExp('\[(\d+)\]\[(\d+)\]');
    
    if(!thisRegex.test(text)){
        alert('fail');
    }
    

    我发现这个测试在提供布尔返回的情况下会表现出更多的preg_匹配。但是,您必须声明一个regexp变量。

    提示:regexp添加了它自己的/在开始和结束时,所以不要传递它们。

        4
  •  5
  •   Dan Stocker    14 年前

    这应该有效:

    var matches = text.match(/\[(\d+)\][(\d+)\]/);
    var productId = matches[1];
    var shopId = matches[2];
    
        5
  •  4
  •   Tim Pietzcker    14 年前
    var myregexp = /\[(\d+)\]\[(\d+)\]/;
    var match = myregexp.exec(text);
    if (match != null) {
        var productId = match[1];
        var shopId = match[2];
    } else {
        // no match
    }