0

I wish to find a character such as ',' in a string unless it is surrounded by double quotes.

For example in the string: 'Example, "String,"'

I would like it to match the comma after 'Example' but not after 'String'.

Is there a regex that can do this?

  • did you mean if the strings is exactly like "\n" or something like "something \n something else "? – Rob Dec 10 '18 at 13:02
  • Have added an example.Sorry about not adding one earlier. – Danial Masood Dec 10 '18 at 13:04
  • 3
    If you're parsing CSV, regexes is usually not the way to go. See https://stackoverflow.com/questions/8493195/how-can-i-parse-a-csv-string-with-javascript-which-contains-comma-in-data for more info. – georg Dec 10 '18 at 13:18

2 Answers2

2

You can negate a group of characters in regex by using (?![text]).

For example, something like (?!"),(?!") would find all the , that are not "touched" by ". You may need to check your string with multiple variations of this regex to get the desired result but I think you should be able to work wit the given example.

David3103
  • 125
  • 10
  • Do all browsers' javascript implementation handle negative lookahead? – mplungjan Dec 10 '18 at 13:27
  • 1
    This is wrong,because it don't work if remove space between `,` and "String,".`('Example,"String,"')` – Ehsan Dec 10 '18 at 13:52
  • @mplungjan Lookbehind is supported in ES2018. I couldn't find a standard in which lookahead support was added, but earlier stackoverflow questions suggest it has been implemented for a long time (for example [this question from 2011](https://stackoverflow.com/questions/6851921/negative-lookahead-regular-expression)). – David3103 Dec 10 '18 at 13:53
  • @Ehsan thank you for the comment, I clarified what the regex in my answer will find. – David3103 Dec 10 '18 at 14:02
  • @Ehsan - that could possibly be non-interesting if all real commas were followed by a space – mplungjan Dec 10 '18 at 15:07
0

Something like this?

console.log(
  `For example in the string: 'Example, "String,"'`.match(/, /g).length,
  `For example, in the following string: 'Example, "String," I'd like to find all ","'`.match(/, /g).length,
)  
mplungjan
  • 169,008
  • 28
  • 173
  • 236