Thread Rating:
  • 2 Vote(s) - 3 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tutorial] Regular Expressions
#1
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.

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)
Reply


Messages In This Thread
[Tutorial] Regular Expressions - by Wolskie - 01-14-2010, 08:06 PM
RE: [Tutorial] Regular Expressions - by Gaijin - 01-14-2010, 08:08 PM
RE: [Tutorial] Regular Expressions - by Wolskie - 01-14-2010, 08:15 PM
RE: [Tutorial] Regular Expressions - by Gaijin - 01-14-2010, 08:17 PM
RE: [Tutorial] Regular Expressions - by Wolskie - 01-14-2010, 08:21 PM
RE: [Tutorial] Regular Expressions - by Gaijin - 01-14-2010, 08:23 PM
RE: [Tutorial] Regular Expressions - by Jordan L. - 01-15-2010, 06:32 AM

Forum Jump:


Users browsing this thread: 1 Guest(s)