11

Replace the character if it is not preceded or followed by the same character

 2 years ago
source link: https://www.codesd.com/item/replace-the-character-if-it-is-not-preceded-or-followed-by-the-same-character.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Replace the character if it is not preceded or followed by the same character

advertisements

I am trying to replace non-consecutive single quotes in a string with two consecutive quotes.

Examples (in/out)

  • "abc'def" --> "abc''def"
  • "abc''de'f" --> "abc''de''f"

Javascript doesn't support lookbehinds, so the following regular expression I'd use with Java (well, more or less) will not compile:

myString.replace(/(?<!)'(?!'))/g, "''");

I have looked around SO and some answers advise using a non-capturing group containing a custom character class negating the character that would otherwise be in the negative lookbehind:

myString.replace(/(?:[^'])'(?!'))/g, "''");

However, that will not do either: it will successfully not replace the two consecutive single quotes, but in the "abc''de'f" example, it will "eat" the f when replacing the next single quote with two consecutive single quotes, ending up in:

"abc''de''gh" (see it's missing the f!)

Questions

  • Is there a suitable regex-based solution for this problem?
  • If not, should I just go with a barbaric iteration and indexing of all the input string's characters and painfully build another string from it (please no)?

As multiple (=more than 2) quotes are not an issue for you, you don't actually need to take that much care, if there are one or two quotes at a given place, just - so just replace every occurence of quotes with the wanted double quotes. The regex for this would be /'+/g and can be replaced by "''"


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK