I’m trying to understand why my example regex does not work the way I’d like to:
test-text: Filename: test myFile 123 .txt
pattern: (?<=Filename:.*?myFile)(.*?)(?=.txt)
Expected Result: 123
I know lookahead/behind is not ideal here, but it’s just for learning purpose trying to understand.
So why does .*?myFile not work? If I remove it, the pattern matches test myFile 123. But I want to look for Filename:, then exclude everything up to myFile, and take everything after and bewteen the last .txt statement. What am I missing here?
Due to the complexities of regex matching, a variable-length lookbehind pattern is not supported. You should get an error message to that effect. This is simply a limitation of Perl’s regex engine.
There is a somewhat similar feature which allows this:
\Kdiscards everything to the left from the final match. So this pattern will probably work as you expect it to:It is not the same as a true lookbehind, however, in that it doesn’t allow overlapping matches.
Incidentally, this is now the third similar question you have posted. Based on the information you have given, the correct answer is still “don’t use look-arounds for this”. If there is a reason you want to use them, you should explain that so we can give better help.