javascript 逗号后跟空格或仅逗号的正则表达式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12368628/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 16:02:05  来源:igfitidea点击:

regex for comma followed by space or just comma

javascriptregex

提问by DVM

is it possible to make a regex with multiple delimiters? For example I want to split a string which can come in two forms: 1. "string1, string2, string3" or 2. "string1,string2,string3". I've been trying to do this in javascript but with no success so far.

是否可以使用多个分隔符制作正则表达式?例如,我想拆分一个字符串,它可以有两种形式:1.“string1,string2,string3”或 2.“string1,string2,string3”。我一直试图在 javascript 中做到这一点,但到目前为止没有成功。

回答by David says reinstate Monica

Just use a regex split():

只需使用正则表达式split()

var string = "part1,part2, part3, part4,    part5",
    components = string.split(/,\s*/);

JS Fiddle demo.

JS小提琴演示

The reason I've used *rather than ?is simply because it allows for no white-space or many white-spaces. Whereas the ?matches zero-or-one white-space (which is exactly what you asked, but even so).

我使用*而不是的原因?仅仅是因为它允许没有空格或许多空格。而?匹配零个或一个空格(这正是您所要求的,但即便如此)。

Incidentally, if there might possibly be white-spaces preceding the comma, then it might be worth amending the split()regex to:

顺便说一句,如果逗号前面可能有空格,那么可能值得将split()正则表达式修改为:

var string = "part1,part2  , part3, part4,    part5",
    components = string.split(/\s*,\s*/);
console.log(components);?

JS Fiddle demo.

JS小提琴演示

Which splits the supplied string on zero-or-more whitespace followed by a comma followed by zero-or-more white-space. This may, of course, be entirely unnecessary.

它将提供的字符串拆分为零个或多个空格,后跟一个逗号,后跟零个或多个空格。当然,这可能完全没有必要。

References:

参考:

回答by Jo?o Silva

Yes, make the whitespace (\s) optional using ?:

是的,使用以下方法将空格 ( \s)设为可选?

var s = "string1,string2,string3";
s.split(/,\s?/);

回答by dejjub-AIS

In addition to silva

除了席尔瓦

just in case you have doubt it can have more than one space then use (or no space)

以防万一你怀疑它可以有多个空格然后使用(或没有空格)

var s = "string1, string2,  string3";
s.split(/,\s*/);