Regular Expressions

From Logic Wiki
Jump to: navigation, search


Some Examples

^  : beginning of a line 

$  : end of a line 

|A : start of a string 

|Z : end of a string 

.  : any character

\w : any letter, digit or underscore

\W : anything that doesn't match \w 

\d : any digit

\D : anything not digit

\s : whitespace (space, tab, newline, ...)

\S : non whitespace 

*  : match zero or more occurances of preceding character and match as many as possible

? : 0 or 1 repetions

* : 0 or more repetions

{n} : \d{1,5}  one to 5 chars of decimal

[ ] :Calend[ae]r [a-z] -> a to z [0-9] -> 0 to 9 [A-Fa-t0-4] -> A to F or a to t or 0 to 4]

'(Jennifer|Jen|Jenny)\b\w+\b' -> any Jennifer with a surname 

'Je(nnifer|nny\n){1,6}\b\w+\b'


Regex in Ruby

/[aeiou]/ : list of characters

/[A-Z]/ : capital letters

String#match

The String#match method converts a pattern to a Regexp (if it isn‘t already one), and then invokes its match method on the target String object. Here is how you find the characters from a String which are next to a whitespace:

'RubyMonk Is Pretty Brilliant'.match(/ ./)