【问题标题】:TS/JS split part of a string from regex matchTS/JS 从正则表达式匹配中拆分字符串的一部分
【发布时间】:2018-12-08 02:44:41
【问题描述】:

过去,我有这个正则表达式:

\{(.*?)\}

并输入了这个字符串:

logs/{thing:hi}/{thing:hello}

然后我使用了以下内容:

console.log(string.split(regex).filter((_, i) => i % 2 === 1));

要得到这个结果:

thing:hi
thing:hello

出于不相关的设计原因,我我的正则表达式更改为:

\{.*?\}

但是现在,当使用相同的测试字符串和分割命令时,它只返回这个:

/

想要它返回这个:

{thing:hi}
{thing:hello}

如何修改拆分(或其他任何内容)来做到这一点?

【问题讨论】:

  • 为什么不matchs.match(/{.*?}/g)

标签: javascript regex typescript split match


【解决方案1】:

为什么不使用match

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match

match() 方法在将 字符串正则表达式 进行匹配时检索匹配项。

如果您只对返回两个字符串匹配感兴趣,那么它比使用split 简单得多。

var foo = "logs/{thing:hi}/{thing:hello}";
console.log(foo.match(/{.*?}/g));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-25
    • 1970-01-01
    • 2012-02-09
    • 2015-10-25
    • 2010-09-15
    • 1970-01-01
    相关资源
    最近更新 更多