我想分隔一个字符串。
"5 tablespoons unsalted butter, melted and cooled, 1 tablespoon, softened, for brushing muffin cups, 2 cups cornmeal"
我想得到:
5 tablespoons unsalted butter, melted and cooled
1 tablespoon, softened, for brushing muffin cups
2 cups cornmeal
The pattern is: , <any number>
I did some search online and tried .split(/(, \d+)/)
. But, it doesn't work as it give me five results. Can i get some help?
谢谢!
Your
(, \d+)
pattern is wrapped with a capturing group and that is why split method returns both matches (comma + space + 1+ digits) and non-matches (the rest).您可以使用
The
/,\s*(?=\d+\b)/
regex matches,
- a comma\s*
- 0+ whitespaces(?=\d+\b)
- followed with 1+ digits and a word boundary.我不知道这是否可以改善,但是也许尝试一下:
The resulting array in
result
is what you're asking for.