简体   繁体   English

在 JavaScript 中使用正则表达式在字符串上拆分逗号

[英]Split commas on string with regular expression in JavaScript

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,'', de', '0', None"

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.目前,我正在使用带有正则表达式的 split 方法,它在 JAVA 上运行良好。 Now I have to handle it by JavaScript but I have got an unexpected result!现在我必须通过 JavaScript 来处理它,但我得到了一个意想不到的结果!

Could you please give me an advice?你能给我一个建议吗?

Thanks for your help!谢谢你的帮助!

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.当您在传递给Java 中String#split()的正则表达式中使用捕获组时,捕获组不会添加到生成的拆分字符串数组中。 In JavaScript , String#split() adds all captured substrings into the resulting array.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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM