javascript - 在 TypeScript 中使用关键字正则表达式获取字符串的一部分

标签 javascript c# regex typescript

我有以下正则表达式:

{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/

相关文章:

javascript - js原型(prototype),设置名称

javascript - 投票: AJAX update count

javascript - 删除 ng-repeat 而不会泄漏

c# - 如何将 C# 用户控件嵌入到 Windows 资源管理器中?

javascript - 有人可以帮助用 javascript 解释这个正则表达式吗?

python - 分析 DNA 序列中的串联重复基序

javascript - 使用setTimeout(fn, 0)和不使用的区别

c# - GDI+画线算法

c# - 使用 java 未达到预期结果,但使用 c# 可以达到预期结果

java - 分离正则表达式中的突发部分