Regex "does not contain" pattern issue for Natural Language Processing

Viewed 56

Link to the regex101

I am implementing a simple NLP algo. I have already implemented the solution looping over the raw string to assist the regex, but now I want to see if I can do it in pure regex.

I can't figure out how to get the 'build' group to respect the negative look ahead. I am trying to capture ["Natural Language Processing" algorithms] Any help will be greatly appreciated, thanks

$subject_string = <<<'subject_string'
Projects I've built & Plan to build. HackMatch.io (May 2020 onward), 
As of October 2020, I intend to start implementing "Natural Language Processing" algorithms 
in PHP when I have time. I'll then use PHP to upload the results to big data tech (e.g. BigQuery) 
to create some data visualizations.
subject_string;

$pattern = <<<'pattern'
/\b(?'verb'build|make|implementing)
(?'build'.+?(?!build|make|implementing)) 
(?=\bin\b|\bon\b)
(?:build|make|implementing)??/ix
pattern;

preg_match_all($pattern, $subject_string, $matches)
1 Answers

You can use

/\b(?'verb'build|make|implementing)\s*
(?'build'(?:(?!(?&verb)).)*?) 
(?=\s*\b(?:in|on)\b)/ixs

See the regex demo. Details:

  • \b - a word boundary
  • (?'verb'build|make|implementing) - Group "verb": one of the words inside parentheses
  • \s* - zer or more whitespaces
  • (?'build'(?:(?!(?&verb)).)*?) - Group "build": any char, zero or more occurrences but as few as possible, that does not start any of the char sequences defined in the "verb" group
  • \s* - zer or more whitespaces
  • (?=\b(?:in|on)\b) - a positive lookahead that matches a location immediately followed with a whole word in or on.
Related