REGEX combining regex strings then finding everything but the matches

Viewed 46

I have two regex strings:

  1. [^'"0-9+\-%*\/<>\!=&|]
  2. (['"])(?:\\\1|.)*?\1

The first one finds anything but the listed characters. The second one finds anything between quotes, including the quotes.

I want to merge these so that I find anything that matches these characters or group of characters between quotes, excludes the matches it found, and returns everything else. For example in the following phrases, I want it to return only the bolded characters.

Hello world "This is a test"
"Another test" 5 x 4
'And this has an escaped quote don\'t in it ' Blue Boy
"This has a single quote ' but doesn't end the quote as it started with double quotes"
hello
28 + 2 / 10 * 3 abc
" Lorem ipsum dolor\" sit 'amet' "

Is this possible? Any help would be appreciated.

1 Answers

You may use a PCRE pattern like

(?:(['"])(?:\\\1|.)*?\1|\d+(?:\s*[*\/+x-]\s*\d+)*)(*SKIP)(*F)|(?=\S)[^'"0-9+\-%*\/<>\!=&|]+

See the regex demo

Details

  • (?:(['"])(?:\\\1|.)*?\1|\d+(?:\s*[*\/+x-]\s*\d+)*)(*SKIP)(*F) - either a substring between " or ' chars or 1+ digits followed with 0 or more occurrences of /, +, -, * or x enclosed with 0+ whitespaces and then 1+ digits, the match is discarded and the next match is searched for from the location of the failure
  • |
  • (?=\S) - next char must be a non-whitespace char
  • [^'"0-9+\-%*\/<>\!=&|]+ - 1 or more chars other than the chars specified inside the negated character class.
Related