【问题标题】:RegEx: Get a string between % signs excluding the signs正则表达式:获取 % 符号之间的字符串,不包括符号
【发布时间】:2014-01-21 02:24:10
【问题描述】:

例如在字符串中

'apple %cherry% carrots %berries2%'

我想提取以下内容:

[
 'cherry',
 'berries2'
]

我已尝试使用以下 RegEx,但它们都包含 % 符号:

/%[a-zA-Z\d]+%/g

我根据我在此处找到的 RegEx 制作了这个 RegEx:Regex to match string between %

如果有什么不同,下面是我提取字符串的方法:http://jsfiddle.net/pixy011/APab8/

【问题讨论】:

    标签: javascript regex


    【解决方案1】:

    试试这个正则表达式:

    /[a-zA-Z\d]+(?=%)/g
    

    (?= ... ) 是一个肯定的前瞻,这基本上意味着它检查以确保内容在字符串中,而不是实际捕获它们。

    第一个% 不需要,因为%[a-zA-Z\d] 不匹配。

    试运行:

    var matches = 'apple %cherry% carrots %berries2%'.match(/[a-zA-Z\d]+(?=%)/g);
    console.log(matches); // => ["cherry", "berries2"]
    

    【讨论】:

    • 但是如果字符串也有apple% 也会导致问题。
    【解决方案2】:

    这应该可行:

    var re = /%([^%]*)%/g,
        matches = [],
        input = 'apple %cherry% carrots %berries2%';
    while (match = re.exec(input)) matches.push(match[1]);
    
    console.log(matches);
    ["cherry", "berries2"]
    

    【讨论】:

      猜你喜欢
      • 2021-11-24
      • 2011-07-17
      • 2010-09-29
      • 2015-07-05
      • 1970-01-01
      • 2013-07-20
      • 2018-07-30
      相关资源
      最近更新 更多