tags:

views:

85

answers:

3

Hay all, i need help making a regex. The string must contain a "-" and must not contain a ".".

Can someone help me please.

+13  A: 

You don't need a regex for that:

if (strpos($string, '-') !== false && strpos($string, '.') === false)
    //do what you want...
Franz
strpos() is more efficient than regex matches, especially in cases like this. This is the perfect answer. +1
Duroth
strpos has to scan the string twice, a good regexp only once!
reto
@reto: True. Would have to run a benchmark to havee the "real" comparison. But in a simple case like this it probably does not matter, I think... Do you agree?
Franz
@Duroth: Efficiency and performance are not the same.
Gumbo
Franz: I dont really like the outcome of that particular regexp (it looks a bit akward), but for the 99 other cases a regexp is much more cleaner and explicit. And this strpos-0-might-be-false-lets-use-===-akwardness only makes it worse.So for me the regexp is the simpler solution, but this is a matter of taste.. your opinion might differ.
reto
Yeah, I see your point. I agree regexes are often cleaner, but sometimes they are harder to read - especially if you're not too experienced with them. Then again: you're right, strpos() isn't the most easy one to read, either ;)
Franz
+1 for not answering the question by the book, but instead giving a better answer
Peter Lindqvist
+3  A: 

Don't know about php, but this should do it:

^[^.]*-[^.]*$
Kobi
Don't forget the anchors! `^` and `$`
Tomalak
@Tomalak - Thanks!
Kobi
To make it more performant, use `^[^.-]*-[^.]*$`.
Gumbo
@Gumbo: Sharp eyes, as always. ;-)
Tomalak
Can you explain why it does make it more performant? I'm not that good with regexes... ;)
Franz
@Franz: Since the `*` quantifier is greedy, the preceeding expression `[^.]` would consume as much as it can before backtracking will be used to match the rest of the expression. So if the test string is `foo-bar`, `[^.]*` will first match the whole string, then step back until `[^.]*-` matches `foo-` and then match the rest so that the whole expression matches. With `[^.-]*` the expression will always just match the `foo` without backtracking.
Gumbo
Cool. Thanks, Gumbo.
Franz
@Gumbo - thanks for that. The though did cross my mind, but I wasn't sure it's necessary. I'll read. Thanks!
Kobi
+2  A: 

no need regex for this, one method is to use strpos

strpos($mystr,"-" ) !== FALSE && strpos($mystr,"." ) === FALSE
ghostdog74