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
#2
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
Reply
#3
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
Reply
#4
OK I see thanks, but the =~ is new to me!
What does it stand for?
Reply
#5
=~ Is a operator used to check if a particular part of the string matches the regex.
Reply
#6
Awsome man, you've been a great help... Thanks...
Reply
#7
Ah, brilliant tut mate. That's awesome!
Thanks for sharing. Smile
At the top will be the same place you hang from.
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)