Thursday, September 24, 2009

REGEX

Regular Expressions You Should Know


Visit Source

href="http://net.tutsplus.com/tutorials/other/8-regular-expressions-you-should-know/%20

Matching a username

/^[a-z0-9_-]{3,16}$/

String that matches: my-us3r_n4m3

String that doesn't match: th1s1s-wayt00_l0ngt0beausername (too long)


Matching a Password

/^[a-z0-9_-]{6,18}$/

String that matches: myp4ssw0rd

String that doesn't match: mypa$$w0rd (contains a dollar sign)


Matching a Hex Value

/^#?([a-f0-9]{6}|[a-f0-9]{3})$/

String that matches:

#a3c113

String that doesn't match:

#4d82h4 (contains the letter h)


Matching a Slug

/^[a-z0-9-]+$/

String that matches:

my-title-here

String that doesn't match:

my_title_here (contains underscores)


Matching an Email

/^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/

String that matches:

john@doe.com

String that doesn't match:

john@doe.something (TLD is too long)


Matching a URL

/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/

String that matches:

http://net.tutsplus.com/about

String that doesn't match:

http://google.com/some/file!.html (contains an exclamation point)


Matching an IP Address

/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/

String that matches:

73.60.124.136 (no, that is not my IP address :P)

String that doesn't match:

256.60.124.136 (the first group must be "25" and a number between zero and five)


Matching an HTML Tag

/^<([a-z]+)([^<]+)*(?:>(.*)<\/\1>|\s+\/>)$/

String that matches:

Nettuts+

String that doesn't match:

" /> (attributes can't contain greater than signs)

No comments: