Skip to content
Advertisement

regex skip match if its follows by whitespace and a keyword

Currently trying to match comments with regexes but only if no function follows. Currently I use a regex which also matches the keyword function. And then check in the source code (php) if this group is set or not.

//**.*?*/s*(function)?/sg

https://regex101.com/r/l0j1ip/1

Now the question is whether it is possible to realize with pure regex. I have tried it with a simple negative lookahead but without success. Although the comment is no longer made individually, but then just with the subsequent comment.

//**.*?*/s*(?!function)/sg

https://regex101.com/r/PuUUw6/1

Next I tried non capture group. But also there without success.

/(?:/**.*?*/s*function)|/**.*?*/s*/sg

https://regex101.com/r/wkQE7E/1

After a comment with the information (*SKIP)(*FAIL) I also tried it without success. All matches above this keyword are skipped. Also the single matches are skipped.

//**.*?*/s*function(*SKIP)(*FAIL)|/**.*?*//sg

https://regex101.com/r/OJSFrF/1

Advertisement

Answer

After reading the question again, it should be doable using negative lookahead ; the repetition must be inside the negative expression:

//**((?!*/).)**/(?!s*function)/sg

Seems you need to understand better how backtracking works, using .*? instead of .* means the regex engine will try first to match everything after before .* however the negative lookahead makes the match fail and .* continues to match. Using ((?!*/).)* can’t match */ wheras .*? can, after backtracking. Another solution is to use atomic group (?>/**.*?*/)(?!s*function).

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement