Corona SDK and other Game Development Tutorials
@gamebuilding

Regular Expressions

If you’re like me, then Regular Expressions can look like ancient greek. So, I’ve put together a list of commonly used phrases with a short explanation of how the expression can be used.

Regular Expressions -> Regular Expression Definition
An example of the regular expression.

. -> will match any character expect a line break
Hello World. matches Hello World. or Hello World!

\. -> the slash escapes a character and will then look for a period
Hello World\. only matches Hello World.

? -> makes the preceding token optional, just means the previous character can be there or not. Only refers to one character.
Hello World\.? will match Hello World. and Hello World

(phrase)? -> by including parenthesis makes an entire sequence of characters optional.
(Hello)? World will match Hello World and World.

[abc] -> matches any single character in the set

\r -> refers to carriage return
\n -> new lines
\s -> space characters
gr[ea]y will match grey or gray

[ABCabc] -> will match either upper case or lower case using character classes
[tT]he will match the or The

g+ -> will match 1 or more preceding tokens, note: g* will match 0 or more of the preceding tokes
asdfgggggggg will match all of the ‘g’ in the string

| -> is the equivalent to the ‘or’ operator
(https?|ftp):// with match http://, https://, or ftp://
(ht|f)tps?://.+ will match http://thatssopanda.com, https://www.google.com or ftp://favorite.com

^ -> looks for a character at the beginning of the string
^H will match the H in Hello. This will not match the H in World Hello.
^Hello$ will match only Hello and not match Hello World. The dollar sign signifies the end of a the string.

One of the more common uses for the carrot symbol is looking up file extensions.
\.jpg$ will match only .jpg
(jpg|gif|png)$ will match only jpg, gif, or png at the end of a string
^.+(jpg|gif|png)$ will match myfile.jpg, myphoto.gif or landscape.png

\d -> will look up any digit 0 through 9
If the string we are looking up is 658-456-1234…
\d\d\d will match 658
\d{3} will match 658, 456, or 123
^\d{3} will match 658
\d{3,4}$ will match 1234

\w -> will look up any alpha numeric character or underscore
If the string we are looking up is Hello World
\w will match H
\w{5} will match Hello

[a-z] -> will only match non capitalized letters
[a-z] will match e in the string Hello

[a-zA-Z] -> will match regardless of capitalization.

Leave a Reply