ceckenrode
ceckenrode

Reputation: 4703

Regex to match 0 or an even number of consecutive characters?

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?

Upvotes: 2

Views: 243

Answers (2)

bobble bubble
bobble bubble

Reputation: 18490

I think it can also be unrolled:

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

See this demo at regex101

Upvotes: 3

anubhava
anubhava

Reputation: 785108

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 '

Upvotes: 4

Related Questions