簡體   English   中英

在Javascript中提取正則表達式中的文本

[英]Extract text in Regular Expression in Javascript

在Javascript中,我想從字符串中提取數組。 字符串是

var str = "abc (24 314 83 383)(-256)sa 0 (24 314) 1"

我希望優先級是括號中的文本,然后是由空格分隔的其他文本。 所以對於上面的例子,結果應該是:

result[0] = "abc"
result[1] = "24 314 83 383"
result[2] = "-256"
result[3] = "sa"
result[4] = "0"
result[5] = "24 314"
result[6] = "1"

我試過了

var pattern = /(.*?)[\s|\)]/g;
result = str.match(pattern);

但結果是: abc ,(24 ,314 ,83 ,383),(-256),sa ,0 ,(24 ,314),

你可以試試這個:

 let str = "abc (24 314 83 383)(-256)sa 0 (24 314) 1"; let replaced = str.replace(/(\\s*\\(|\\))/g, '<REP>'); let arrFromStr = replaced.split('<REP>').filter(w => w.length != 0); 

變量“被替換”替換所有1)0或更多空格+“(”和2)所有“)”符號到“”字符串。 arrFromStr從string創建一個數組並用“”分割它。 然后我們檢查數組的元素是否為空。

這是一個使用正則表達式對象和exec的解決方案,它比使用str.match(/\\w+|\\((.*?)\\)/g).map(e => e.replace(/^\\(|\\)$/g, ""))等過濾掉括號更安全str.match(/\\w+|\\((.*?)\\)/g).map(e => e.replace(/^\\(|\\)$/g, ""))

 var str = "abc (24 314 83 383)(-256)sa 0 (24 314) 1"; var reg = /\\w+|\\((.*?)\\)/g; var match; var res = []; while (match = reg.exec(str)) { res.push(match[1] || match[0]); } console.log(res); 

嘗試這個:

 var str = "abc (24 314 83 383)(-256)sa 0 (24 314) 1" var pattern = /\\((.*?)\\)|\\s?(\\S+)\\s?/g; var result = str.match(pattern).map(v => v.trim().replace(/^\\(|\\)$/g, '')); console.log(result) 

暫無
暫無

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

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