我有以下正则表达式:
{thing:([^}]*)}
这完全匹配 '{thing:' 和 '}',并且中间允许任何 !}。
在 C# 中,我只能使用以下代码获取中间的内容:
regex.Matches(stringToCheckForMatches).Cast<Match>().Select(x => x.Groups[1].Value);
在 TypeScript 中是否有等效的方法来获取中间内容?另请注意,stringToCheckForMatches 可以包含 {thing:} 关键字的多个实例(具有任何中间内容)。
例如,我想要这个:
'fooBar/{thing:hi}{thing:hello}'
要返回(最好是在数组/列表中):
hi
hello
或者,如果您无法访问 TypeScript 中的 .match 捕获(老实说我不确定),是否有办法将正则表达式更改为仅捕获“{thing:”之后的内容并且前 '}'?那也行。
最佳答案
按正则表达式拆分结果为 ["fooBar/", "hi", "", "hello", ""]
:
console.log( 'fooBar/{thing:hi}{thing:hello}'.split(/{thing:([^}]*)}/) );
和filter
可以用来获取奇数元素:
console.log( 'fooBar/{thing:hi}{thing:hello}'.split(/{thing:([^}]*)}/).filter((_, i) => i & 1) );
或
console.log( 'fooBar/{thing:hi}{thing:hello}'.split(/.*?{thing:(.*?)}.*?/).filter(Boolean) );
没有正则表达式的替代方案:
var str = 'fooBar/{thing:hi}{thing:hello}'
console.log( str.split('{thing:').slice(1).map(s => s.split('}')[0]) );
关于javascript - 在 TypeScript 中使用关键字正则表达式获取字符串的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50996835/