How to String.match() distinct it ${SOME_TEXT} usi

2019-02-20 04:44发布

I need this string:

var x = 'Hi ${name}! How are you? ${name}, you are old! ${name} share with ${other} how do u ${feel}!'

I need to know using Regex how much distinct ${ANY_THING} exists. In example above i expect 3: ${name}, ${other}, ${feel}

I'm trying it:

x.match(\${([a-zA-Z]))

But the output is wrong :(

Thanks!

3条回答
何必那么认真
2楼-- · 2019-02-20 05:21

I find this solution at #regex IRC Channel by farn user:

x.match(/\$\{([^\}]+)\}(?![\S\s]*\$\{\1\})/g);

output:

['${name}',
 '${other}',
 '${feel}']

and

x.match(/\$\{([^\}]+)\}(?![\S\s]*\$\{\1\})/g).length;

output:

3

:)

查看更多
地球回转人心会变
3楼-- · 2019-02-20 05:36

I need to know using Regex how much distinct ${ANY_THING} exists

x.match(/\$\{[^\}]+\}/g)
 .sort()
 .filter(function(element, index, array) {
     return index == array.indexOf(element);
 }) // this .filter() filters out the duplicates (since JS lacks of built in
    // unique filtering functions
 .length;

The code above would return 3, as that's how many distinct items are in the x string.

JSFiddle: http://jsfiddle.net/cae6P/

PS: It's not possible to do it with regular expression only. You need to filter duplicates using the .filter() solution or some other similar

查看更多
唯我独甜
4楼-- · 2019-02-20 05:42

To match the syntax you want you need this:

x.match(/\$\{([a-zA-Z]+)\}/)
查看更多
登录 后发表回答