This section describes the regular expressions and Ruby Regular Expressions in ruby.
A regular expression is a character of a special sequence. It matches or searches for other strings or string sets by using a pattern with special syntax.
Syntax
A regular expression is literally a pattern between a slash or any separator following % r, as shown below:
/Pattern // pattern/im # You can specify the option % r! /Usr/local! # General separator Regular Expression instance #! /Usr/bin/ruby line1 = "Cats are smarter than dogs"; line2 = "Dogs also like meat"; if (line1 = ~ /Cats (. *)/) puts "Line1 contains Cats" endif (line2 = ~ /Cats (. *)/) puts "Line2 contains Dogs" end
This produces the following results:
Line1 contains Cats
Regular Expression Modifier
A regular expression may literally contain an optional modifier used to control all aspects of matching. The modifier is specified after the second slash, as shown in the preceding example. The subscript lists possible modifiers:
Just as strings are separated by % Q, Ruby allows you to start with % r as a regular expression followed by any separator. This is useful when the description contains a large number of slash characters that you do not want to escape.
# Match a single slash character below without escaping % r |/| # use the following syntax to match % r [</(. *)>] I
Regular Expression Mode
Besides the control characters? . * ^ $ () [] {}| \). All other characters match themselves. You can place a backslash before the control character to escape the control character.
The following table lists the regular expression syntaxes available in Ruby.
Search and replace
Sub and gsub and their substitution variables sub! And gsub! Is an important string method when using regular expressions.
All these methods use the regular expression mode to perform the search and replacement operations. Sub and sub! The first appearance of the replacement mode, gsub and gsub! All occurrences of the replacement mode.
Sub and gsub return a new string, keeping the original string unchanged, while sub! And gsub! The strings they call will be modified.
The following is an example:
#! /Usr/bin/ruby phone = "2004-959-559 # This is Phone Number" # Delete the Ruby comment phone = phone. sub! (/#. * $/, "") Puts "Phone Num: # {phone}" # Remove characters other than numbers from phone = phone. gsub! (/\ D/, "") puts "Phone Num: # {phone }"
This produces the following results:
Phone Num : 2004-959-559Phone Num : 2004959559
The following is another instance:
#! /Usr/bin/ruby text = "rails are rails, really good Ruby on Rails" # change all "rails" to "Rails" text. gsub! ("Rails", "Rails") # change all the words "Rails" to uppercase text. gsub! (/\ Brails \ B/, "Rails") puts "# {text }"
This produces the following results:
Rails are Rails, really good Ruby on Rails