我有一个由正斜杠分隔的字符串,通配符以 $
开头表示:
/a/string/with/$some/$wildcards
我需要一个正则表达式来获取所有通配符(没有“$”),其中通配符可以在它们前面有更多的“字符串”(并且下一个字符应该始终是正斜杠)或者将在末尾字符串。这是我所在的位置(它匹配字符串的末尾而不是下一个“/”):
//Just want to match $one
var string = "/a/string/with/$one/wildcard"
var re = /\$(.*)($|[/]?)/g
var m = re.exec(string)
console.log(m);
// [ '$one/wildcard',
// 'one/wildcard',
// '',
// index: 123,
// input: '/a/string/with/$one/wildcard'
// ]
这是之前的一次尝试(不考虑字符串末尾的通配符):
//Want to match $two and $wildcards
var string = "/a/string/with/$two/$wildcards"
var re = /\$(.*)\//g
var m = re.exec(string)
console.log(m);
// [ '$two/',
// 'two',
// '',
// index: 123,
// input: '/a/string/with/$two/$wildcards'
// ]
我四处搜索以匹配字符串的字符 或 结尾并找到了几个答案,但没有一个试图解释多个匹配项。我认为我需要能够将下一个字符匹配为 /
贪婪地,然后然后尝试匹配字符串的结尾。
所需的功能是获取输入字符串:
/a/string/with/$two/$wildcards
并将其转换为以下内容:
/a/string/with/[two]/[wildcards]
提前致谢!另外,很抱歉,如果已经明确详细地涵盖了这一点,经过各种搜索后我无法找到副本。
最佳答案
我认为应该这样做:
/\$([^\/]+)/g
您可以使用 replace()
函数:
"/a/string/with/$two/$wildcards".replace(/\$([^\/]+)/g, "[$1]");
// "/a/string/with/[two]/[wildcards]"
关于javascript - 正则表达式以获取所有带有可选下一个字符或字符串结尾的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33743033/