【问题标题】:Get Text between parenthesis using jQuery使用jQuery获取括号之间的文本
【发布时间】:2017-12-12 13:24:48
【问题描述】:

我试图在以 {{

开头的多个花括号之间获取值

例如:

var txt ="I expect five hundred dollars {{$500}}. and new brackets {{$600}}";

预期结果:array of result like result[0] = "{{$500}}", result[1] = "{{$600}}"

我尝试了下面的东西,但它没有返回预期的结果

var regExp = /\{([^)]+)\}/g;
var result = txt.match(regExp);

JsFiddle Link

【问题讨论】:

标签: javascript jquery


【解决方案1】:

您可以使用像/{{\w+:(\$\d+)}}/g 这样的简单正则表达式,然后使用RegExp#exec 函数获取每个匹配项并从捕获的组中提取值。

var txt = "I expect five hundred dollars {{rc:$500}}. and new brackets {{ac:$600}}";

var reg = /{{\w+:(\$\d+)}}/g,
  m,
  res = [],
  res2 = [];

while (m = reg.exec(txt)) {
  res.push(m[0]);
  res2.push(m[1]);
}

console.log(res,res2)

【讨论】:

  • @Richa : /{{rc(\$\d+)}}/g
  • @Richa : /{{rc:(\$\d+)}}/g
  • @Richa 分享预期结果
  • @Richa :您可以根据需要更新正则表达式,您可以使用自己的正则表达式匹配大括号之间除括号之外的任何内容的组合
  • jsfiddle.net/mnsvp6qn/3 不能在更新的小提琴中工作。我错过了什么
【解决方案2】:

使用matchmap,正则表达式为/(?:({{))[^}]+(?=}})/g

var txt ="I expect five hundred dollars {{ac:$500}}. and new brackets {{ac:$600}}";
var matches = txt.match( /(?:({{))[^}]+(?=}})/g );
if ( matches )
{
   matches = matches.map( s => s.substring(2) );
}
console.log( matches  );

演示

var txt ="I expect five hundred dollars {{ac:$500}}. and new brackets {{ac:$600}}";
var matches = txt.match(/(?:({{))[^}]+(?=}})/g);
if (matches) {
  matches = matches.map(s => s.substring(2));
}
console.log(matches);

【讨论】:

    【解决方案3】:

    像这样改变你的代码

    var txt ="I expect five hundred dollars {{$500}}. and new brackets {{$600}}";
    function getText(str) {
      var res = [], p = /{{([^}]+)}}/g, row;
    
      while(row = p.exec(str)) {
        res.push(row[1]);
      }
      return res;
    }
    console.log(getText(txt)); 

    【讨论】:

      【解决方案4】:

      String#match 将始终返回完全匹配的正则表达式,而不使用捕获组。您可以使用 String#replace 和回调函数将每个匹配项添加到数组中。

      var txt ="I expect five hundred dollars {{ac:$500}}. and new brackets {{ac:$600}}";
      
      var regExp = /{{ac:([^\}]+)}}/g;
      
      function matches(regExp, txt) {
        const result = []
        txt.replace(regExp, (_, x) => result.push(x));
        return result
      }
      
      console.log(matches(regExp, txt))
      <script src="https://codepen.io/synthet1c/pen/KyQQmL.js"></script>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-17
        • 1970-01-01
        • 2019-03-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多