簡體   English   中英

TS / JS從正則表達式匹配中拆分字符串的一部分

[英]TS/JS split part of a string from regex match

過去,我有這個正則表達式:

\{(.*?)\}

並輸入以下字符串:

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

然后,我使用了以下內容:

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

要獲得此結果:

thing:hi
thing:hello

由於無關的設計原因,我正則表達式更改為:

\{.*?\}

但是現在,當使用相同的測試字符串和拆分命令時,它僅返回以下內容:

/

希望它返回此:

{thing:hi}
{thing:hello}

如何修改拆分(或其他任何方法)以執行此操作?

為什么不使用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)); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM