简体   繁体   中英

Extract text in Regular Expression in Javascript

In Javascript, I want to extract array from a string. The string is

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

I want priority to be the text in parentheses then other text separated by white space. So for the above example, the result should to be:

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"

I tried

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

but the result was: abc ,(24 ,314 ,83 ,383),(-256),sa ,0 ,(24 ,314),

You can try this:

 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); 

Variable "replaced" replaces all 1) 0 or more spaces + "(", and 2) all ")" symbols to "" string. arrFromStr creates an array from string and split it with "". Then we check is the element of array empty, or not.

Here's a solution using a regex object and exec , which is safer than filtering out parenthesis with something like 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); 

try this:

 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) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM