2

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!

3
  • 1
    ?? using .split(',') should work! what unexpected result are you getting? Commented Oct 16, 2017 at 14:26
  • @Fallenhero: He doesn't want to split 'Abc,' in that input. That comma is part of the string, it's not a separator. Commented Oct 16, 2017 at 14:30
  • no, it's not! As you can see my input, there is some cases one of them has comma inside. 'Abc,'', de' is one element. Commented Oct 16, 2017 at 14:31

1 Answer 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.

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));

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.