gpt4 book ai didi

javascript - 如何 String.match() 使用正则表达式区分它 ${SOME_TEXT}

转载 作者:行者123 更新时间:2023-11-30 08:03:58 25 4
gpt4 key购买 nike

我需要这个字符串:

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

我需要使用 Regex 知道有多少不同的 ${ANY_THING} 存在。在上面的例子中我期望 3: ${name}, ${other}, ${feel}

我正在尝试:

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

但是输出是错误的:(

谢谢!

最佳答案

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;

上面的代码将返回 3,因为这是 x 字符串中有多少个不同的项目。

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

PS: 只用正则表达式是不行的。您需要使用 .filter() 解决方案或其他类似的解决方案来过滤重复项

关于javascript - 如何 String.match() 使用正则表达式区分它 ${SOME_TEXT},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21292764/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com