【问题标题】:How can i obtain a string between two specific strings using regex?如何使用正则表达式获取两个特定字符串之间的字符串?
【发布时间】:2015-01-23 14:30:50
【问题描述】:

我有一个这样的字符串,

green open calldetails  1 0 4 0 10.7kb 10.7kb 
green open stocksummary 1 0 3 0  8.6kb  8.6kb

我需要从中获取 Stocksummary 和 calldetails。 这是我尝试使用正则表达式的方法,

var result = string.match(/(?:open )(.+)(?:1)/)[1];

这是我的全部功能:

routerApp.controller("elasticindex",function($scope,es){
  es.cat.indices("b",function(r,q){
   String St = string.match(/(?:open )(.+)(?:1)/)[1];
  console.log(r,q);
});
});

所需的输出:

calldetails
stocksummary 

【问题讨论】:

    标签: javascript html regex angularjs


    【解决方案1】:

    这个非贪婪(惰性)正则表达式应该可以代替:

    /open +(.+?) +1/
    

    RegEx Demo

    var result = string.match(/open +(.+?) +1/)[1];
    

    或安全的方法:

    var result = (string.match(/open +(.+?) +1/) || ['', ''])[1];
    

    代码:

    var re = /open +(.+?) +1/g,
        matches = [],
        input = "green open calldetails 1 0 4 0 10.7kb 10.7kb green open stocksummary 1 0 3 0 8.6kb 8.6kb";
    while (match = re.exec(input)) matches.push(match[1]);
    console.log(matches);
    

    JsFiddle Demo

    【讨论】:

    • 它给出公开股票摘要 1
    • 问题是g 标志,现在已修复。检查我的更新版本。
    • 它工作正常,我有一个小问题。因为它是一个字符串,“green open calldetails 1 0 4 0 10.7kb 10.7kb green open stocksummary 1 0 3 0 8.6kb 8.6kb”我如何单独获取索引。我怎样才能得到 calldetails 和 stocksummary?
    猜你喜欢
    • 2014-12-08
    • 1970-01-01
    • 2017-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-04
    相关资源
    最近更新 更多