Wednesday, January 16, 2013

Regular Expression Examples


*     
Zero or more occurrences of the previous character or subexpression. For example, 7*8 matches   7778 or just 8.

One or more occurrences of the previous character or subexpression. For example, 7+8 matches 7778 but not 8.

( ) 
Groups a subexpression that will be treated as a single element. For example, (78)+ matches 78 and 787878.

{m,n} 
The previous character (or subexpression) can occur from m to n times. For example, A{1,3} matches A, AA, or AAA.

Either of two matches. For example, 8|6 matches 8 or 6.

[ ] 
Matches one character in a range of valid characters. For example, [A-C] matches A, B, or C.

[^ ] 
Matches a character that isn’t in the given range. For example, [^A-B] matches any character except A and B.

Any character except newline. For example, .here matches where and there.

\s 
Any whitespace character (such as a tab or space).

\S 
Any nonwhitespace character.

\d 
Any digit character.

\D 
Any character that isn’t a digit.

\w 
Any “word” character (letter, number, or underscore).

\W 
Any character that isn’t a “word” character (letter, number, or underscore).

E-mail address*    \S+@\S+\.\S+ 
Check for an at (@) sign and dot (.) and allow nonwhitespace characters only. 

Password        \w+ 
Any sequence of one or more word characters (letter, space, or underscore). Specific-length password \w{4,10} A password that must be at least four characters long but no longer than ten characters.

Advanced password         [a-zA-Z]\w{3,9} 
As with the specific-length password, this regular expression will allow four to ten total characters. The twist is that the first character must fall in the range of a–z or A–Z (that is to say. it must start with a nonaccented ordinary letter).

Another advanced password        [a-zA-Z]\w*\d+\w* 
This password starts with a letter character, followed by zero or more word characters, one or more digits, and then zero or more word characters. In short, it forces a password to contain one or more numbers somewhere inside it. You could use a similar pattern to require two numbers or any other special character.

Limited-length field        \S{4,10} 
Like the password example, this allows four to ten characters, but it allows special characters (asterisks, ampersands, and so on).

U.S. Social Security number     \d{3}-\d{2}-\d{4} 
A sequence of three, two, then four digits, with each group separated by a dash. You could use a similar pattern when requiring a phone number.

No comments:
Write comments
Recommended Posts × +