Home > Back-end >  Regex to match 0 or an even number of consecutive characters?
Regex to match 0 or an even number of consecutive characters?

Time:10-08

I'm looking to see if it's possible to have a regex pattern that matches content between enclosing single quotes in a string, with the requirement that single quotes are escaped using another single quote.

Example:

The quick 'brown fox ''jumped ''''over the lazy dog''';

The regex should capture this string: 'brown fox ''jumped ''''over the lazy dog'''. Since a single quote is escaped using another single quote here, the rest of the string isn't included.

This is what I have so far (?<!\')\'(?!\'). (?<!\')\'(?!\')

This almost works, except the group isn't captured if the closing non-escaped single quote has an escaped quotes before it.

Is it possible to change the negative lookbehind to say that a single quote should be matched if there are either 0 or an EVEN number of single quotes behind it?

CodePudding user response:

You may use this regex without any look around:

'((?:[^'] |'')*)'

RegEx Demo

RegEx Breakup:

  • ': Match a '
  • (: Start a capture group
    • (?::
      • [^'] : Match 1 of any char that is not a '
      • |: OR
      • '': Match a pair of quotes i.e. ''
    • )*: End non-capture group. Repeat this group 0 or more times
  • ): End capture group
  • ': Match a '

CodePudding user response:

I think it can also be unrolled:

'[^']*(?:''[^']*)*'

See this demo at regex101

  • Related