gpt4 book ai didi

javascript - TS/JS 从正则表达式匹配中拆分字符串的一部分

转载 作者:行者123 更新时间:2023-11-30 14:31:35 25 4
gpt4 key购买 nike

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

\{(.*?)\}

然后输入这个字符串:

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

然后我使用了以下内容:

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

要得到这个结果:

thing:hi
thing:hello

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

\{.*?\}

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

/

希望它返回这个:

{thing:hi}
{thing:hello}

我如何修改拆分(或其他任何东西)来执行此操作?

最佳答案

为什么不使用匹配

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

The match() method retrieves the matches when matching a string against a regular expression.

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

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

关于javascript - TS/JS 从正则表达式匹配中拆分字符串的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51092681/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com