Yuri Stiopin
Yuri Stiopin

Reputation: 105

JavaScript RegEx splitting on math operators while keeping them as separate items

I got strings like this

5 +var +"HEH"
5 +"HEllo!"
5

I need to parse it with RegEx, so as result I need to have an array

['5', '+', 'var', '+', '"HEH"']

['5', '+', '"HEH"']

['5']

I've tried something like

/(".+"|\d(?:\.\d+)*)(?:\s*(\+)\s*(".+"|\d(?:\.\d+)*|\w+))*/

But it returns only first matching group and last.

['5', '+', '"HEH"']

['5', '+', '"HEllo!"']

['5']

!Update .split() can't be used because parsing values can be written without whitespaces. Sorry for not complete description

Upvotes: 2

Views: 178

Answers (4)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626748

You can use split with a regex matching and capturing all the math operators:

s.split(/\s*([-\/*+=])\s*/)

Note the = sign is included here, you may remove it if you do not need to split on the equals sign.

See the JavaScript demo:

const texts = ['5 +var +"HEH"','5 +"HEllo!"','5', '12+3-4='];
const regex = /\s*([-\/*+=])\s*/;
for (const text of texts) {
    console.log(text, "=>", text.split(regex));
}

See the regex demo. Remember that String#split pushes capturing group values to the resulting array:

If separator is a regular expression that contains capturing parentheses, then each time separator is matched the results (including any undefined results) of the capturing parentheses are spliced into the output array.

Upvotes: 0

Vikash Yadav
Vikash Yadav

Reputation: 71

You don't need to use complex regex in any case. Try this -

First, replace all " +" with " + " and then use split method.

var str = '5 +var +"HEH"';
str.replace(/ \+/g, " + ");

Now use split() method -

console.log(str.split(" ")); 

var str = '5 +var +"HEH"';
str = str.replace(/ \+/g, " + ");
console.log(str.split(" "));

Upvotes: 1

prasanth
prasanth

Reputation: 22490

Why need a regex simply do with split()

var a ='5 + var + "HEH"'

console.log(a.split(" "))

Regex Method Try this pattern (\d+)|"(\w+)"|(\w+)|(\+|-|\*|\/|=|>|<|>=|<=|&|\||%|!|\^|\(|\))

Demo

Upvotes: 1

Ali Mamedov
Ali Mamedov

Reputation: 5256

You can try this:

let str_1 = '5 + var + "HEH"';
let str_2 = '5 + "HEllo!"';
let str_3 = '5';
let regex = /\s([\+])\s/;

console.log(str_1.split(regex));
console.log(str_2.split(regex));
console.log(str_3.split(regex));

The split() method splits a String object into an array of strings by separating the string into substrings.

Syntax: str.split([separator[, limit]])

The separator is treated as a string or a regular expression.

Upvotes: 2

Related Questions