【问题标题】:Get a portion of a string using a keyword regex in TypeScript在 TypeScript 中使用关键字正则表达式获取字符串的一部分
【发布时间】:2018-06-23 00:04:06
【问题描述】:

我有以下正则表达式:

{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:' 之后的内容和前 '}'?那也行。

【问题讨论】:

    标签: javascript c# regex typescript


    【解决方案1】:

    用正则表达式分割得到["fooBar/", "hi", "", "hello", ""]:

    console.log( 'fooBar/{thing:hi}{thing:hello}'.split(/{thing:([^}]*)}/) );

    和filter 可用于获取奇数元素:

    console.log( 'fooBar/{thing:hi}{thing:hello}'.split(/{thing:([^}]*)}/).filter((_, i) =&gt; i &amp; 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]) );

    【讨论】:

      猜你喜欢
      • 2014-01-20
      • 2021-12-10
      • 2021-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-12
      • 1970-01-01
      相关资源
      最近更新 更多