简体   繁体   中英

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"

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

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!

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. In JavaScript , String#split() adds all captured substrings into the resulting array.

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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