用JavaScript中的正则表达式分割字符串中的逗号

时间:2021-11-26 21:27:18

I'm beginner at regular expression. I need your advice on it.

我是正则表达式初学者。我需要你的建议。

I want to split a string by commas which are outside a couple of single quote with regular expression.

我想用逗号分隔一个字符串,它位于带有正则表达式的单引号之外。

Regex pattern: ,(?=([^']*'[^']*')*[^']*$)

正则表达式模式:,(? =((^ ']*[^]*)*(^)* $)

String input: "'2017-10-16 10:44:43.0000000', 'Abc,'', de', '0', None"

字符串输入:““2017-10-16 10:44:43.0000000”、“Abc”,德”、“0”,没有“

Expected output: ["'2017-10-16 10:44:43.0000000'", " 'Abc,'', de'", " '0'", " None"] there is an array with 4 elements.

期望输出:['2017-10-16 10:44:43.0000000'" " Abc ", " de ", " 0 ", " None"]有一个包含4个元素的数组。

Currently, I'm using split method with regex and It's working well on JAVA. Now I have to handle it by JavaScript but I have got an unexpected result!

目前,我正在使用regex的split方法,它在JAVA上运行良好。现在我必须用JavaScript来处理它,但是我得到了一个意想不到的结果!

Could you please give me an advice?

你能给我一个建议吗?

Thanks for your help!

谢谢你的帮助!

1 个解决方案

#1


2  

Your regex contains a capturing group, ([^']*'[^']*').

你的正则表达式包含一个捕获组,([^ ']*[^]*)。

When you use a capturing group in a regex that you pass to String#split() in Java, the capturing groups are not added to the resulting split array of strings. In JavaScript, String#split() adds all captured substrings into the resulting array.

当您在regex中使用一个捕获组,并将其传递给Java中的String#split()时,捕获组不会被添加到结果的分割字符串数组中。在JavaScript中,String#split()将所有捕获的子字符串添加到结果数组中。

To make the pattern compatible between the two engines, just turn the capturing group with a non-capturing one,

要使模式在两个引擎之间兼容,只需将捕获组转换为非捕获组,

,(?=(?:[^']*'[^']*')*[^']*$)
    ^^^            ^

See the regex demo.

查看演示正则表达式。

JS demo:

JS演示:

var rx = /,(?=(?:[^']*'[^']*')*[^']*$)/;
var s = "'2017-10-16 10:44:43.0000000', 'Abc,'', de', '0', None";
console.log(s.split(rx));

#1


2  

Your regex contains a capturing group, ([^']*'[^']*').

你的正则表达式包含一个捕获组,([^ ']*[^]*)。

When you use a capturing group in a regex that you pass to String#split() in Java, the capturing groups are not added to the resulting split array of strings. In JavaScript, String#split() adds all captured substrings into the resulting array.

当您在regex中使用一个捕获组,并将其传递给Java中的String#split()时,捕获组不会被添加到结果的分割字符串数组中。在JavaScript中,String#split()将所有捕获的子字符串添加到结果数组中。

To make the pattern compatible between the two engines, just turn the capturing group with a non-capturing one,

要使模式在两个引擎之间兼容,只需将捕获组转换为非捕获组,

,(?=(?:[^']*'[^']*')*[^']*$)
    ^^^            ^

See the regex demo.

查看演示正则表达式。

JS demo:

JS演示:

var rx = /,(?=(?:[^']*'[^']*')*[^']*$)/;
var s = "'2017-10-16 10:44:43.0000000', 'Abc,'', de', '0', None";
console.log(s.split(rx));