Aladdin
Aladdin

Reputation: 1337

php regular expression backslash dash

I'm new in PHP and I'm trying to accommodate php regular expression

from w3schools this regular expression

"/([\w\-]+\@[\w\-]+\.[\w\-]+)/"

represents the e-mail regular expression, but I'm wondering what this class definition means "[\w\-]", \w any word character but what about "\-"?

(Edited)

Upvotes: 3

Views: 6845

Answers (4)

Rahul Tripathi
Rahul Tripathi

Reputation: 172448

[\w\-] means letters(capital and small letter both) and numbers including -(dash/hypen)

You may check your regex explanation here

[\w\-]+ match a single character present in the list below

Quantifier: Between one and unlimited times, as many times as possible, giving back as needed [greedy]

\w match any word character [a-zA-Z0-9_]

\- matches the character - literally

Upvotes: 4

Fletcher Rippon
Fletcher Rippon

Reputation: 1975

All [\w\-] Means is match and word character \w and match any - \-

it means the exact same thing as [\w-]

Upvotes: 1

hwnd
hwnd

Reputation: 70732

But what about \- ?

The hyphen is mostly a normal character in regular expressions.

  • Outside of a character class; it has no special meaning (do not need to escape the hyphen).
  • Inside of a character class it has special meaning.

You can place a hyphen as the first or last character of the class without escaping.

  • ( [-\w], [\w-] )

In some regular expression implementations, you can also place directly after a range without escaping.

Simply escaping the hyphen as the last character of the class is fine here.

[\w\-]  # any character of: word characters (a-z, A-Z, 0-9, _), 
        # match a literal hyphen `\-'

Upvotes: 8

sunbabaphu
sunbabaphu

Reputation: 1493

\w matches any word character plus _, underscore, i.e. upper and lowercase alphabets, numbers 0 to 9 and underscore.
\- matches a normal dash.

so [\w\-] would allow numbers, alphabets, underscores and dashes in the email alias.
(it should be noted that \., which allows a dot, is not included for the regex before @ although, .s are allowed for email aliases)

Upvotes: 0

Related Questions