POSIX and PCRE compliant regex to extract a word

34 Views Asked by At

I want to extract a string whether it is at the beginning of a sentence or the end it has to be the whole word. The expression should work in both PCRE and POSIX.

Example:

input strings=['ALLY [&] MORTY','[&] ME', '[&]']
---> match is in bracket
1

There are 1 best solutions below

0
Barmar On
(^| )(&)( |$)
  • (^| ) matches either the beginning of the string or a space
  • (&) matches the literal string &.
  • ( |$) matches either a space or the end of the string.

The match will be in capture group 1.