Regex (PCRE) Match words between words

Viewed 63

Hi! I have a problem with correct PCRE expression. Need cath bolder words (animal's names) in sample text:

this animal is called Hippo and can overcome no more than
is called Hippo and can overcome no more than
Hippo and can overcome no more than
Hippo can overcome no more than
this animal is called Grey Rabbit and can overcome no more than
this animal is called Small Grey Rabbit can overcome no more than
This is a test. Animal is called Small Grey Rabbit can overcome no more than

Here is the expression was i made. Unfortunately i cannot made it work correct, pls help. {1,3} quantifier if it possible need replace with * (Matches 0 or more of the preceding token.)

(^|called )\K([a-z]* ?){1,3}(?=( and)? can overcome)
1 Answers

You can use

(?:^|called\s+)\K[A-Z][a-z]*(?:\s+[A-Z][a-z]*)*?(?=(?:\s+and)?\s+can\s+overcome)

See the regex demo. Details:

  • (?:^|called\s+) - start of string or called and one or more whitespaces
  • \K - match reset operator
  • [A-Z][a-z]* - an upper letter and zero or more lowercase letters
  • (?:\s+[A-Z][a-z]*)*? - zero or more but as few as possible occurrences of one or more whitespaces, an upper and then zero or more lowercase letters
  • (?=(?:\s+and)?\s+can\s+overcome) - a positive lookahead that matches a location that is immediately followed with
    • (?:\s+and)? - an optional occurrence of zero or more whitespaces and and
    • \s+can\s+overcome - zero or more whitespaces, can, zero or more whitespaces, overcome.
Related