正则表达式以获取所有出现的可选下一个字符或字符串结尾
regex to get all occurrences with optional next character or end of string
我有一个由正斜杠分隔的字符串,通配符以 $
:
开头表示
/a/string/with/$some/$wildcards
我需要一个正则表达式来获取所有通配符(没有“$”),其中通配符可以在它们前面有更多 "string"(下一个字符应该始终是正斜杠)或者将是在字符串的末尾。这是我所在的位置(它匹配字符串的末尾而不是下一个“/”):
//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'
// ]
我四处搜索以匹配字符 或 字符串结尾并找到了几个答案,但 none 试图解释多个匹配项。我 think 我需要能够匹配下一个字符作为 /
greedily 和 then 尝试匹配字符串的结尾。
所需的功能是获取输入字符串:
/a/string/with/$two/$wildcards
并将其转换为以下内容:
/a/string/with/[two]/[wildcards]
提前致谢!另外,很抱歉,如果已经明确详细地介绍了这一点,经过各种搜索后我无法找到副本。
我认为应该这样做:
/$([^\/]+)/g
并且您可以使用 replace()
函数:
"/a/string/with/$two/$wildcards".replace(/$([^\/]+)/g, "[]");
// "/a/string/with/[two]/[wildcards]"
您可以像这样在字符串上使用 replace
函数:
var s = '/a/string/with/$two/$wildcards';
s.replace(/$([a-zA-Z]+)/g, '[]')';
s
的值为:
/a/string/with/[two]/[wildcards]
这是替换文档的参考 https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/replace
我有一个由正斜杠分隔的字符串,通配符以 $
:
/a/string/with/$some/$wildcards
我需要一个正则表达式来获取所有通配符(没有“$”),其中通配符可以在它们前面有更多 "string"(下一个字符应该始终是正斜杠)或者将是在字符串的末尾。这是我所在的位置(它匹配字符串的末尾而不是下一个“/”):
//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'
// ]
我四处搜索以匹配字符 或 字符串结尾并找到了几个答案,但 none 试图解释多个匹配项。我 think 我需要能够匹配下一个字符作为 /
greedily 和 then 尝试匹配字符串的结尾。
所需的功能是获取输入字符串:
/a/string/with/$two/$wildcards
并将其转换为以下内容:
/a/string/with/[two]/[wildcards]
提前致谢!另外,很抱歉,如果已经明确详细地介绍了这一点,经过各种搜索后我无法找到副本。
我认为应该这样做:
/$([^\/]+)/g
并且您可以使用 replace()
函数:
"/a/string/with/$two/$wildcards".replace(/$([^\/]+)/g, "[]");
// "/a/string/with/[two]/[wildcards]"
您可以像这样在字符串上使用 replace
函数:
var s = '/a/string/with/$two/$wildcards';
s.replace(/$([a-zA-Z]+)/g, '[]')';
s
的值为:
/a/string/with/[two]/[wildcards]
这是替换文档的参考 https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/replace