我试图使用正则表达式拆分以下字符串,使每个单词,括号,逗号和空格分成字符串。我尝试了很多次,却找不到合适的模式。
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%",")"," ","("," ",")" ......]
有没有人知道如何解决这个问题?
非常感谢你的帮助, 尼科
答案 0 :(得分:2)
根据您自己想要的输出,您真正需要的是:
([\s,()])
JS代码:
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,()])/));

答案 1 :(得分:0)
我不确定我的意图是否正确,但我会说你可以使用这个简单的正则表达式:
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)
在这里,您可以查看正则表达式:https://regex101.com/r/1yYCSN/1
正则表达式输出:var string = ["WHEAT"," ","flour"," ","(", "49%",")"," ","("," ",")" ...]
您期望输出:var string = ["WHEAT"," ","flour"," ","(", "49%",")"," ","("," ",")" ......]
希望我能提供帮助。