Regular expressions are a special sequence of characters that can help match or find other strings or string sets, using patterns that maintain a specialized syntax.
The regular expression literal is a pattern between a slash or any delimiter%r as follows:
Grammar:
Copy Code code as follows:
/pattern/
/PATTERN/IM # option can be specified
%r!/usr/local! # General Delimited Regular expression
For example:
#!/usr/bin/ruby
line1 = "Cats are smarter than";
Line2 = "Dogs also like meat";
if (line1 =~/cats (. *)/)
puts ' Line1 starts with Cats '
end
if (line2 =~ (. *)/)
/cats "puts Line2 With Dogs ' End
This will produce the following results:
Regular expression modifiers:
The text of a regular expression can include an optional modifier to control all aspects of the match. After you modify the specified second slash character, as shown earlier, you can represent one of these characters:
%q separates string literals, Ruby allows regular expressions to be%r and then delimited by the selected delimiter. This is useful when the described pattern contains a forward slash character that does not want to be escaped:
# following matches a single slash character, no escape required
%r|/|
# Flag characters are allowed with this syntax, too%r[</
(. *) >]i
Regular expression pattern:
Except for the control character, (+?. * ^ $ () [] {} | \), all characters match. You can escape the control character preceded by a backslash.
Search and Replace:
The string method is most important, using regular expression sub and gsub, they are in situ variants sub! and gsub!
All of these methods use a regular expression pattern during a search and replace operation. Sub & sub! Replaces all occurrences of the pattern Gsub & gsub! that appear for the first time.
sub! and gsub! Returns a new string, unmodified original sub and gsub they are called modified strings.
The following example:
#!/usr/bin/ruby
phone = "2004-959-559 #This is phone number"
# Delete Ruby-style comments
phone = phone.sub! ( /#.*$/, "")
puts "Phone Num: #{phone}"
# Remove anything other than digits
Phone = phone.gsub! ( /\d/, "")
puts "Phone Num: #{phone}"
This will produce the following results:
Phone num:2004-959-559
Phone num:2004959559
Here is another example:
#!/usr/bin/ruby
Text = "Rails are rails, really good ruby on Rails"
# change ' rails ' to ' rails ' throughout
text.gsub! ("Rails", "rails")
# capitalize the word "Rails" throughout
text.gsub! ( /\brails\b/, "Rails")
puts "#{text}"
This will produce the following results:
Rails are rails, really good Ruby on rails