0

Trying to use RegEx to split the following string:

"C=US,ST=NY,O=GOOGLE\, INC"

The intention is for O=GOOGLE\, INC to stay intact after splitting on comma.

12
  • What about \\, does that stay intact? Commented Oct 10, 2014 at 18:08
  • 1
    Maybe just split using regex (?<!\\), Commented Oct 10, 2014 at 18:09
  • The idea is to not split on commas that that are preceded by '\' or '\\' characters. Commented Oct 10, 2014 at 18:10
  • If you don't care about odd/even `\`, use that regex in split. Commented Oct 10, 2014 at 18:13
  • 3
    Javascript does not support look-behind. Commented Oct 10, 2014 at 18:17

2 Answers 2

1

If you can do without split, you can just use a regex like this that captures field data.
edit - Modified to match spurious escapes as well.

 #  /(?:^|,)((?:[^,\\]*(?:\\,|\\)?)+)(?:(?=,)|$)/

 (?: ^ | , )            # Leading comma or BOL
 (                      # (1 start), Field data
      (?:
           [^,\\]* 
           (?: \\, | \\ )?
      )+
 )                      # (1 end)
 (?:                    # Lookahead, comma or EOL
      (?= , )
   |  $ 
 )

Output >>

 **  Grp 0 -  ( pos 0 , len 4 ) 
C=US  
 **  Grp 1 -  ( pos 0 , len 4 ) 
C=US  

--------------

 **  Grp 0 -  ( pos 4 , len 6 ) 
,ST=NY  
 **  Grp 1 -  ( pos 5 , len 5 ) 
ST=NY  

--------------

 **  Grp 0 -  ( pos 10 , len 15 ) 
,O=GOOGLE\, INC  
 **  Grp 1 -  ( pos 11 , len 14 ) 
O=GOOGLE\, INC  
Sign up to request clarification or add additional context in comments.

Comments

0

Your data looks like it will be fairly reliably of the form:

foo=bar,spic=span,a=bob\,fred

ie, pairs of key=val data, with escaped commas in the data. So if the escaped commas are only in the data, then you can use a simple lookahead for the 'key=' as part of your regexp. Assuming the key is always in capitals, then this works:

s = "C=US,ST=NY,O=GOOGLE\, INC"
s.split(/,(?=[A-Z]*=)/)

ie, split on a comma if it is followed by some capitals and an equals.

This will give you

["C=US", "ST=NY", "O=GOOGLE, INC"]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.