Find all phrases enclosed with (" ") and words without (" ") in an expression

Viewed 75

Language being used: PHP

Lets say I have an expression like this:

Ayala NOT ("Ayala Station" OR "Ayala Branch" OR "Joey Ayala")

And I want to extract the following words:
- Ayala
- Ayala Station
- Ayala Branch and
- Joey Ayala

I want to retrieve all phrases enclosed in double quotation mark " " and stand-alone words like the Ayala in the example above, but failed with experiments

Tried multiple regex

1st attempt:

"([^"]+)" - I'm aware that this regex is the correct one for getting words/phrases inside double quotation mark

2nd attempt:

~\w+(?:-\w+)*~ - this regex will get all words from a given expression or string

3rd attempt:

Combining the 2 attempts above "([^"]+)"|~\w+(?:-\w+)*~ - I was able to produce my use cases for my desired output but with these 2 combined, the Ayala word isn't being extracted

Example playground regex101

4th attempt:

Tried using "([^"]+)"|\S+ but it is including the special characters

4th Attempt

Am I missing something with the regex?

1 Answers

The right side of the alternation should not have regex delimiters - the regex delimiters should only be around the entire pattern (next to the PHP string delimiters). Eg

"([^"]+)"|\w+(?:-\w+)*

If you want to capture all matches at once, without capture groups, you can use

(?<=")\b[^"]+(?=")|\w+(?:-\w+)*

https://regex101.com/r/nP6wM5/10

To exclude NOT and OR in the regex itself, use:

(?<=")\b[^"]+(?=")|\b(?!(?:NOT|OR)(?!-))\w+(?:-\w+)*

to negative lookahead for them right before matching the standalone words.

Related