First of all, the (?:[^a-zA-Z0-9]|^)
and (?:[^a-zA-Z0-9]|$)
patterns are used here as word boundaries with _
excluded. It makes sense to streamline them and use (?<![^\W_])
and (?![^\W_])
respectively.
Next, the words you have can be processed to create a regex trie out of them for efficient search.
Here is an example code:
from trieregex import TrieRegEx
keywords = ['FIND', 'ANY', 'MATCHING', 'WORD', 'BY', 'THIS', 'VERY', 'LONG', 'REGEX', 'PATTERN', 'PARROT', 'FIGHT']
pattern = fr'(?<![^\W_])({TrieRegEx(*keywords).regex()})(?![^\W_])'
# => (?<![^\W_])((?:PA(?:TTERN|RROT)|FI(?:GHT|ND)|MATCHING|REGEX|LONG|THIS|VERY|WORD|ANY|BY))(?![^\W_])
Just make sure you install trieregex
beforehand.
See the resulting regex pattern.
See also another demo based on this regex trie solution:
import re
class Trie():
"""Regex::Trie in Python. Creates a Trie out of a list of words. The trie can be exported to a Regex pattern.
The corresponding Regex should match much faster than a simple Regex union."""
def __init__(self):
self.data = {}
def add(self, word):
ref = self.data
for char in word:
ref[char] = char in ref and ref[char] or {}
ref = ref[char]
ref[''] = 1
def dump(self):
return self.data
def quote(self, char):
return re.escape(char)
def _pattern(self, pData):
data = pData
if "" in data and len(data.keys()) == 1:
return None
alt = []
cc = []
q = 0
for char in sorted(data.keys()):
if isinstance(data[char], dict):
try:
recurse = self._pattern(data[char])
alt.append(self.quote(char) + recurse)
except:
cc.append(self.quote(char))
else:
q = 1
cconly = not len(alt) > 0
if len(cc) > 0:
if len(cc) == 1:
alt.append(cc[0])
else:
alt.append('[' + ''.join(cc) + ']')
if len(alt) == 1:
result = alt[0]
else:
result = "(?:" + "|".join(alt) + ")"
if q:
if cconly:
result += "?"
else:
result = "(?:%s)?" % result
return result
def pattern(self):
return self._pattern(self.dump())
text = r'FIND ANY MATCHING WORD BY THIS VERY LONG REGEX PATTERN FIGHT FIGHTER PARROT PARROT_ING'
keywords = ['FIND', 'ANY', 'MATCHING', 'WORD', 'BY', 'THIS', 'VERY', 'LONG', 'REGEX', 'PATTERN', 'PARROT', 'FIGHT']
trie = Trie()
for word in keywords:
trie.add(word)
pattern = fr'(?<![^\W_])({trie.pattern()})(?![^\W_])'
print(re.findall(pattern, text))
Output:
['FIND', 'ANY', 'MATCHING', 'WORD', 'BY', 'THIS', 'VERY', 'LONG', 'REGEX', 'PATTERN', 'FIGHT', 'PARROT', 'PARROT']
Note the two occurrences of PARROT
, the last one comes from the PARROT_ING
string part.