簡體   English   中英

如何通過節點中的正則表達式提取 substring 數組?

[英]How can I extract an array of substring via regex in nodes?

我有一個字符串 var,其值為(1,2)(3,4) ,我想從中提取一個數組[[1,2],[3,4]] 我的解決方案是使用str.match但我還沒有弄清楚如何提取數組。 我努力了:

> '(1,2)(3,4)'.match(/([\d]+),([\d])*/)
[ '3,2', '3', '2', index: 1, input: '(3,2)(4,5)', groups: undefined ]

結果不是我想要的。 那么我應該如何處理正則表達式呢?

您需要使用/(\d+),(\d+)/g或 - 僅獲取括號內的內容 - /\((\d+),(\d+)\)/g並使用RegExp#exec獲取結果一個循環:

 var s = '(1,2)(3,4)', m, results=[]; var rx = /(\d+),(\d+)/g; while(m=rx.exec(s)) { results.push([m[1], m[2]]) } console.log(results);

或者,如果您針對最新的 JS 環境,則使用matchAll

 const s = '(1,2)(3,4)', rx = /(\d+),(\d+)/g; const results = [...s.matchAll(rx)]; console.log(Array.from(results, x => [x[1],x[2]]))

還有另一種方法,不使用 RegExp,以防萬一:

 const src = '(1,2)(3,4)', result = src.slice(1,-1).split(')(').map(s => s.split(',')) console.log(result)
 .as-console-wrapper{min-height:100%;}

暫無
暫無

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

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