Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expressions: How to Express \w Without Underscore

Tags:

regex

url

php

Is there a concise way to express:

\w but without _ 

That is, "all characters included in \w, except _"

I'm asking this because I'm looking for the most concise way to express domain name validation. A domain name may include lowercase and uppercase letters, numbers, period signs and dashes, but no underscores. \w includes all of the above, plus an underscore. So, is there any way to "remove" an underscore from \w via regex syntax?

Edited: I'm asking about regex as used in PHP.

Thanks in advance!

like image 945
Dimitri Vorontzov Avatar asked Feb 13 '13 16:02

Dimitri Vorontzov


People also ask

Does regex \W include underscore?

\W matches any character that's not a letter, digit, or underscore. It prevents the regex from matching characters before or after the phrase.

Is underscore a special character in regex?

Regex doesn't recognize underscore as special character.

What does \w represent in regular expression?

\w (word character) matches any single letter, number or underscore (same as [a-zA-Z0-9_] ). The uppercase counterpart \W (non-word-character) matches any single character that doesn't match by \w (same as [^a-zA-Z0-9_] ). In regex, the uppercase metacharacter is always the inverse of the lowercase counterpart.

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string). Both are called anchors and ensure that the entire string is matched instead of just a substring.


2 Answers

the following character class (in Perl)

[^\W_] 

\W is the same as [^\w]

like image 162
protist Avatar answered Sep 19 '22 10:09

protist


You could use a negative lookahead: (?!_)\w

However, I think writing [a-zA-Z0-9.-] is more readable.

like image 20
Bergi Avatar answered Sep 22 '22 10:09

Bergi