Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to detect an odd number of consecutive quotes

If a string contains a single quote ", I need to replace it with double quotes "". However, sometimes a valid double-quote can be followed by a single quote, eg. """, which just needs another quote added to the end. If I use a standard replace, eg. replace('"', '""'), all the quotes are turned into doubles, of course, not just the odd one.

What I need is to find any odd number of consecutive quotes (including a single one on its own) and simply add another quote onto the end. Eg. " becomes "", and """ becomes """".

Is there a regex replace in JavaScript which can accomplish this?

like image 536
ingredient_15939 Avatar asked Mar 21 '23 18:03

ingredient_15939


2 Answers

Are the quotes consecutive? Unless I've misunderstood your requirement, this would work...

str = str.replace(/\"\"?/g, '""')

Explanation: Matches a single quote, optionally followed by another quote, and replaces one/both with two quotes.

Example: http://jsfiddle.net/aR6p2/

Or alternatively, if it's just a matter of appending a quote when there's an odd number of quotes in a string...

  var count = str.split('"').length - 1
  str = str + (count % 2 == 0 ? '' : '"')
like image 98
Nick Grealy Avatar answered Apr 01 '23 00:04

Nick Grealy


You can just do this:

var str = '"" """" """ """""';
var re = /([^"]|^)"("")*(?!")/g;
console.log(str.replace(re, '$1(quotes)')); // '"" """" (quotes) (quotes)'

What that does is the following:

  • it matches a non-quote - or the start of the entered string - first, and stores it in the first capturing group
  • then it matches one double-quote
  • then a group of 2 double-quotes, for any amount of times (0 or more)
  • it then checks if the next character is a non-quote, but without actually matching it.
  • This is then replaced by the value captured by the first capturing group (the non-quote), and the string (quotes).

Basically, it just replaces any odd amount of double-quotes with (quotes).

Demo

like image 26
Joeytje50 Avatar answered Apr 01 '23 01:04

Joeytje50