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

社会主义新天地 提交于 2019-12-01 09:51:50

问题


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!


回答1:


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




回答2:


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:


To match the syntax you want you need this:

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


来源:https://stackoverflow.com/questions/21292764/how-to-string-match-distinct-it-some-text-using-regex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!