Sunday, July 5, 2009

Regular expression syntax examples

In order to give you a quick reference to the different patterns and what they will match, here's a comprehensive table of all we've covered. Column one contains example expressions, and column two contains what that expression will match.

Expr


Will match...

foo


the string "foo"

^foo


"foo" at the start of a line

foo$


"foo" at the end of a line

^foo$


"foo" when it is alone on a line

[Ff]oo


"Foo" or "foo"

[abc]


a, b, or c

[^abc]


d, e, f, g, h, etc - everything that is not a, b, or c (^ is "not" inside sets)

[A-Z]


any uppercase letter

[a-z]


any lowercase letter

[A-Za-z]


any letter

[A-Za-z0-9]


any letter of number

[A-Z]+


one or more uppercase letters

[A-Z]*


zero or more uppercase letters

[A-Z]?


zero or one uppercase letters

[A-Z]{3}


3 uppercase letters

[A-Z]{3,}


a minimum of 3 uppercase letters

[A-Z]{1,3}


1-3 uppercase letters

[^0-9]


any non-numeric character

[^0-9A-Za-z]


any symbol (not a number or a letter)

Fo*


F, Fo, Foo, Fooo, Foooo, etc

Fo+


Fo, Foo, Fooo, Foooo, etc

Fo?


F, Fo

.


any character except \n (new line)

\b


a word boundary. E.g. te\b matches the "te" in "late", but not the "te" in "tell".

\B


a non-word boundary. "te\B" matches the "te" in "tell" but not the "te" in "late".

\n


new line character

\s


any whitespace (new line, space, tab, etc)

\S


any non-whitespace character

No comments:

Post a Comment