question about simple regex

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
oboedrew
Forum Commoner
Posts: 78
Joined: Fri Feb 20, 2009 1:17 pm

question about simple regex

Post by oboedrew »

Which of these would be the preferable way to check that a variable contains at least one character that is not a hyphen?

Code: Select all

preg_match('|[^-]+|', $whatever)
or

Code: Select all

preg_match('|[^\-]+|', $whatever)
According to http://www.regular-expressions.info/reference.html, a hyphen should be escaped by a backslash unless the hyphen occurs immediately after a caret. But when I try the two versions in a php script, they both seem to work. Are they interchangeable, or am I missing something?

Thanks,
Drew
User avatar
prometheuzz
Forum Regular
Posts: 779
Joined: Fri Apr 04, 2008 5:51 am

Re: question about simple regex

Post by prometheuzz »

oboedrew wrote:Which of these would be the preferable way to check that a variable contains at least one character that is not a hyphen?

Code: Select all

preg_match('|[^-]+|', $whatever)
or

Code: Select all

preg_match('|[^\-]+|', $whatever)
According to http://www.regular-expressions.info/reference.html, a hyphen should be escaped by a backslash unless the hyphen occurs immediately after a caret. But when I try the two versions in a php script, they both seem to work. Are they interchangeable, or am I missing something?

Thanks,
Drew
Hi Drew,

Yes, they're the same.
For example, these all match a single '*':

Code: Select all

'/[*]/'
// equals
'/[\*]/'
// equals
'/\*/'
What is the "best" is debatable. I prefer to use the least amount of characters in a regex, so I'd opt for option three, or if the character class is larger, go for option 1. I wouldn't use option 2 (but again: that's just me).
Post Reply