Support Forums
[Tutorial] Regular Expressions - Printable Version

+- Support Forums (https://www.supportforums.net)
+-- Forum: Categories (https://www.supportforums.net/forumdisplay.php?fid=87)
+--- Forum: Coding Support Forums (https://www.supportforums.net/forumdisplay.php?fid=18)
+---- Forum: Ruby and Ruby on Rails (https://www.supportforums.net/forumdisplay.php?fid=55)
+---- Thread: [Tutorial] Regular Expressions (/showthread.php?tid=4344)



[Tutorial] Regular Expressions - Wolskie - 01-14-2010

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)



RE: [Tutorial] Regular Expressions - Gaijin - 01-14-2010

Now that was what I was looking for, your fast man!
Thanks for teaching!

How are those objects being used when created...

Edit:
Useful to read when working with Regexp..
http://en.wikipedia.org/wiki/Regular_expression


RE: [Tutorial] Regular Expressions - Wolskie - 01-14-2010

You can use them like this...

Code:
X = regex.new(/abc/)
Y = "xxxxabcxxx"
puts X =~ Y #4

If("abcd" =~ X) then
   puts "true" # Returns true
end



RE: [Tutorial] Regular Expressions - Gaijin - 01-14-2010

OK I see thanks, but the =~ is new to me!
What does it stand for?


RE: [Tutorial] Regular Expressions - Wolskie - 01-14-2010

=~ Is a operator used to check if a particular part of the string matches the regex.


RE: [Tutorial] Regular Expressions - Gaijin - 01-14-2010

Awsome man, you've been a great help... Thanks...


RE: [Tutorial] Regular Expressions - Jordan L. - 01-15-2010

Ah, brilliant tut mate. That's awesome!
Thanks for sharing. Smile