Make regexp shorter
I have the following text: var avarb avar var varb var
. What I want to do is to extract only "direct" var
occurrences. The above str开发者_如何学Cing contains 3 of them.
While playing with rubular I made up the following Regexp: /\A(var)|\s(var)\s|(var)\z/
.
Is there a way to simplify it, in order to use var
substring in regexp only once?
Try this one using word boundaries:
/\bvar\b/
Either use Alexanders version or
/(^|\s)(var)($|\s)/ # or:
/(?:^|\s)(var)(?:$|\s)/ # (?: ) will prevent capturing
If I understand you correctly, you can use lookaheads and lookbehinds:
/(?<=^|\s)(var)(?=$|\s)/
/\s+(var)\+/
would seem sufficient?
精彩评论