1

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:

-.*\s-

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?

1

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

2
‘*?’, ‘+?’, ‘??’
     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

Hence:

-.*?\s-

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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