Mostafa Fouda
Mostafa Fouda

Reputation: 31

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

Upvotes: 1

Views: 10114

Answers (3)

BaseScript
BaseScript

Reputation: 421

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.

Upvotes: 2

ggorlen
ggorlen

Reputation: 56935

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

Upvotes: 2

xianshenglu
xianshenglu

Reputation: 5329

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)

Upvotes: 1

Related Questions