Search code examples
regexregexp-replace

Regex to match dashes(-) within apostrophe(')


I'm trying to write a regular expression to match match dashes(-) only within apostrophe(')

Example Data:

( NOT TABLE-FIELD BEWEEN 'XX-XX'  AND 'XX-XX'  ) AND ( TABLE-FIELD = 'XXX-XXX-XXX' )

Expectation on match - between '' and it should ignore - outside '' example , TABLE-FIELD

( NOT TABLE-FIELD BEWEEN 'XX-XX' AND 'XX-XX' ) AND ( TABLE-FIELD = 'XX-XX-XX' )

Came up with this (')()[^ ]* up to now it will match what's inside ' but not sure what expression to write to limit it down only to -

Result,

( NOT TABLE-FIELD BEWEEN 'XX-XX' AND 'XX-XX' ) AND ( TABLE-FIELD = 'XX-XX-XX' )


Solution

  • If it can be assumed that there are always an even number of single quotes we can infer that a hyphen is within a single-quote-delimited phrase if and only if the number of single quotes following the hyphen in the string is odd. That happens if the following regular expression is matched.

    -(?=[^']*'(?:(?:[^']*'){2})*[^']*$)
    

    Demo