A regular expression for determining an odd number of consecutive quotes

If the string contains a single quote ", I need to replace it with double quotes "". However, sometimes a valid double quote may be followed by a single quote, for example. """that just needs an extra quote added to the end. If I use a standard replacement, for example. replace('"', '""'), all quotes turn into doubles, of course, not only odd ones.

I need to find any odd number of consecutive quotes (including one separately) and just add another quote to the end. For example. "becomes "", but """becomes """".

Replace regex with javascript that can do this?

+4
source share
3 answers

Are quotation marks sequential? If I do not understand your requirement, this will work ...

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

Explanation: Matches one quote, optionally followed by another quote, and replaces one / both with two quotation marks.

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

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

  var count = str.split('"').length - 1
  str = str + (count % 2 == 0 ? '' : '"')
+6
source

You can simply do this:

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

What does it mean:

  • it coincides with some or the beginning of the entered line - first and saves it in the first capture group
  • then it matches one double quote
  • then a group of two double quotes for any number of times (0 or more)
  • , , .
  • , ( ), (quotes).

, (quotes).

+1

Probably a crazy regex that will do this, but for me not to go crazy I would.

str = str.replace(/[^"]("+)/, function(match, group1){
   if((group1.length % 2) === 1 || group1.length === 1){
      return group1+'"';
   }
   return group1;
});
0
source

Source: https://habr.com/ru/post/1524408/


All Articles