1

我有一个包含一个或多个占位符的字符串,格式如下:$( [name] )

[ name]可以是任何单词(包含字母数字字符)并且区分大小写。

 Example1: 'The $(Quick) Brown fox jumps over the lazy dog'
 Example2: '$(the) $(Quick) Brown fox jumps over $(the) lazy dog'
 Example3: '$(the) $(Quick) Brown $(fox) jumps over $(the) lazy $(dog)'

javascript中检索所有占位符的最佳方法是什么,以便我们得到以下结果:

 Example1: ['Quick']
 Example2: ['the', 'Quick', 'the']
 Example3: ['the', 'Quick', 'fox', 'the', 'dog']

我还需要检索占位符的唯一列表,因此:

 Example1: ['Quick']
 Example2: ['the', 'Quick']
 Example3: ['the', 'Quick', 'fox', 'dog']

谢谢你。

4

3 回答 3

2

正如其他答案所提到的,您最好的方法是将正则表达式与 JavaScriptstring.match()函数一起使用。我的正则表达式可能不是最好的 [ who is ],但这应该可以解决问题:

jsFiddle 演示

function getPlaceholders(str)
{
    var regex = /\$\((\w+)\)/g;
    var result = [];

    while (match = regex.exec(str))
    {
        result.push(match[1]);    
    }

    return result;
}

谢谢怪胎 _

于 2012-06-27T08:57:50.373 回答
0

使用带有 字符串匹配函数的正则表达式

于 2012-06-27T08:50:22.207 回答
0

读这个

http://net.tutsplus.com/tutorials/php/advanced-regular-expression-tips-and-techniques/

http://swtch.com/~rsc/regexp/regexp1.html

你可以看到更多Bookmark

于 2012-06-27T08:51:11.450 回答