I want to select (by regexp) only text that start by - and end by whitespace

here text:

test-hello how-are again ok
maybe good but-some not good but-what about this

I use this regexp:


but result is not correct:

enter image description here

The correct result is:

"-x "
"-f "
"-hello "
"-are "
"-some "
"-what "

How I can do this by regexp?

2 Answers 2


The problem is that .* matches anything, and by default it is greedy. In your case, you probably want a non-greedy search: -.*?\s-.

‘*?’, ‘+?’, ‘??’
     These are “non-greedy” variants of the operators ‘*’, ‘+’ and ‘?’.
     Where those operators match the largest possible substring
     (consistent with matching the entire containing expression), the
     non-greedy variants match the smallest possible substring
     (consistent with matching the entire containing expression).

     For example, the regular expression ‘c[ad]*a’ when applied to the
     string ‘cdaaada’ matches the whole string; but the regular
     expression ‘c[ad]*?a’, applied to that same string, matches just
     ‘cda’.  (The smallest possible match here for ‘[ad]*?’ that permits
     the whole expression to match is ‘d’.)

-- C-hig (elisp)Regexp Special



Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.