oldhomemovie
oldhomemovie

Reputation: 15129

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

Upvotes: 0

Views: 83

Answers (4)

Dartoxian
Dartoxian

Reputation: 780

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

Upvotes: 0

Marcel Jackwerth
Marcel Jackwerth

Reputation: 54762

Either use Alexanders version or

/(^|\s)(var)($|\s)/       # or:
/(?:^|\s)(var)(?:$|\s)/   # (?: ) will prevent capturing 

Upvotes: 1

Håvard
Håvard

Reputation: 10080

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

/(?<=^|\s)(var)(?=$|\s)/

Upvotes: 0

Alexander Ivanov
Alexander Ivanov

Reputation: 717

Try this one using word boundaries:

 /\bvar\b/

Upvotes: 5

Related Questions