0

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 string 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?

oldhomemovie
  • 14,621
  • 13
  • 64
  • 99

4 Answers4

5

Try this one using word boundaries:

 /\bvar\b/
Alexander Ivanov
  • 717
  • 4
  • 16
1

Either use Alexanders version or

/(^|\s)(var)($|\s)/       # or:
/(?:^|\s)(var)(?:$|\s)/   # (?: ) will prevent capturing 
Marcel Jackwerth
  • 53,948
  • 9
  • 74
  • 88
0

/\s+(var)\+/ would seem sufficient?

Andrew Grimm
  • 78,473
  • 57
  • 200
  • 338
Dartoxian
  • 750
  • 1
  • 6
  • 10
0

If I understand you correctly, you can use lookaheads and lookbehinds:

/(?<=^|\s)(var)(?=$|\s)/
Håvard
  • 9,900
  • 1
  • 41
  • 46