I want to make a regular expression that is able to do the following:
- Match various words exactly, e.g. {
addpaths,addpath,test} - Exclude lines that start with a
%sign - Exclude matches that are surrounded by quotation marks (
'and")
So I came up with the following regex (with flags g, m):
^[^%]*?(?<=[^\'\"])\b(addpaths|addpath|test)\b(?=[^\'\"]).*?$?
And this gives me the following result (see regex101):
function addpaths() --> match, correct
% function addpaths to add paths to path --> no match, correct
fprintf('running addpaths') --> no match, correct
fprintf('addpaths running') --> no match, correct
fprintf('running addpaths.') --> match, wrong
fprintf('running addpaths function') --> match, wrong
% fprintf('running addpaths') --> no match, correct
% fprintf('addpaths running') --> no match, correct
% fprintf('running addpaths function') --> no match, correct
% test what happens to 'test' --> no match, correct
run('test') --> no match, correct
'this is a test.' --> match, wrong
test --> match, correct
So the regex works when one of the exact matching words is next to a ', but not when there is another word, whitespace or . next to it. Why?
import re
text = '''function addpaths()
% function addpaths to add paths to path
fprintf('running addpaths')
fprintf('addpaths running')
fprintf('running addpaths function')
% fprintf('running addpaths')
% fprintf('addpaths running')
% fprintf('running addpaths function')
% test what happens to 'test'
run('test')
'this is a test.'
test
'''
pattern = '^[^%]*?(?<=[^\'\"])\\b(addpaths|addpath|test)\\b(?=[^\'\"]).*?$'
regex = re.compile(pattern, re.M)
matches = regex.findall(text)
for m in matches:
print(m)