This article mainly introduces the regular expressions in Ruby. It also provides examples for searching and replacing regular expressions, if you need a regular expression, you can refer to it as a special sequence character. 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.
# The following matches a single slash character without escaping % r |/| # The Flag character can be matched using the following syntax. % 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