Regular expressions are used as a flexible way for identifying strings of text.
Basic Regular Expressions.
----------------------------
Regex + Description
----------------------------
/Mark/ - Matches the single work 'Mark'.
/[Mm]ark/ - Matches 'Mark' or 'mark'.
/^ABC/ - Matches 'ABC' at the beginning of the line.
/XYZ$/ - Matches 'XYZ' at the end of the line.
%r([0-9]*) - Matches any order of 0 or more digits.
Commonly used notations in regular expressions
----------------------------
Notation + Meaning
----------------------------
^ - Begining of line.
$ - End of line.
. - Any character except newlines.
\w - Any alphanumerical character.
\W - Not a word character.
\s - Whitespace character, for example a tab or newline.
\S - Non-whitespace character.
\D - Non-Digit.
\d - Digit, for example [0-9].
\A - Begining of string.
Creating New Regular Expressions
Regular expressions can be created using the class method
Regexp.new. Only the first paramater is really required, it maybe either a string
or a regex.
This method can take a second parameter, witch can be one of the following:
Basic Regular Expressions.
----------------------------
Regex + Description
----------------------------
/Mark/ - Matches the single work 'Mark'.
/[Mm]ark/ - Matches 'Mark' or 'mark'.
/^ABC/ - Matches 'ABC' at the beginning of the line.
/XYZ$/ - Matches 'XYZ' at the end of the line.
%r([0-9]*) - Matches any order of 0 or more digits.
Commonly used notations in regular expressions
----------------------------
Notation + Meaning
----------------------------
^ - Begining of line.
$ - End of line.
. - Any character except newlines.
\w - Any alphanumerical character.
\W - Not a word character.
\s - Whitespace character, for example a tab or newline.
\S - Non-whitespace character.
\D - Non-Digit.
\d - Digit, for example [0-9].
\A - Begining of string.
Creating New Regular Expressions
Regular expressions can be created using the class method
Regexp.new. Only the first paramater is really required, it maybe either a string
or a regex.
Code:
regex1 = Regexp.new("^Ruby") # /^Ruby/
regex2 = Regexp.new(/Ruby$/) # /Ruby$/
This method can take a second parameter, witch can be one of the following:
- Regexp::EXTENDED
- Regexp::IGNORECASE
- Regexp::MULTILINE
Code:
regex3 = Regexp.new("test", Regexp::IGNORECASE)
option = Regexp::EXTENDED || Regexp::MULTILINE
regex4 = Regexp.new(/test/, option)