简体   繁体   中英

Javascript regex - Split string with words separated from spaces, commas and parenthesis

I'm trying to split the following string using regex in a way that every word, parenthesis, commas and spaces would be separated into string. I tried many times but can't find the right pattern.

var string = "WHEAT flour (49%) (with calcium, iron, niacin, thiamin), butter (MILK), pasteurised EGG, water, MILK, sugar, fresh yeast, salt, powdered pasteurised EGG"

var string = ["WHEAT"," ","flour"," ","(", "49%",")"," ","("," ",")" ......]

Does anyone have an idea of how to solve this?

Thanks a lot for your help, Nico

Based on your own desired output what you really need is this:

([\s,()])

JS code:

 var string = "WHEAT flour (49%) (with calcium, iron, niacin, thiamin), butter (MILK), pasteurised EGG, water, MILK, sugar, fresh yeast, salt, powdered pasteurised EGG"; console.log(string.split(/([\\s,()])/)); 

I'm not sure if I get your intentions right but I would say you could use this simple regex:

 var string = "WHEAT flour (49%) (with calcium, iron, niacin, thiamin), butter (MILK), pasteurised EGG, water, MILK, sugar, fresh yeast, salt, powdered pasteurised EGG" var array = string.split(/([\\s,()])/); console.log(array) 

Here you can have a look at the regex expression: https://regex101.com/r/1yYCSN/1

Regex output : var string = ["WHEAT"," ","flour"," ","(", "49%",")"," ","("," ",")" ...]

You expected output : var string = ["WHEAT"," ","flour"," ","(", "49%",")"," ","("," ",")" ......]

Hope I could help.

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