开发者

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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜