A regular expression is a special sequence of characters that matches or finds a collection of other strings or strings by using a pattern that has a specialized syntax.
Grammar
A regular expression is literally a pattern between a slash or between any delimiter that follows a%r, as follows:
/pattern/
/pattern/im # can specify option
%r!/usr/local! # General delimited Regular Expression
instance
#!/usr/bin/ruby
line1 = " Cats are smarter than dogs ";
Line2 = "Dogs also like meat";
if (line1 =~/cats (. *)/)
puts "Line1 contains Cats"
end
if (line2 =~ (. *)/)
/cats "puts Line2 Ins Dogs "End
This will produce the following results:
Regular expression modifiers
A regular expression may literally contain an optional modifier to control all aspects of the match. Modifiers are specified after the second slash character, as shown in the previous example. The subscript lists the possible modifiers:
Just as strings are delimited by%q, Ruby allows you to start with%r as a regular expression followed by any delimiter. This is useful when describing a slash character that contains a large number of you do not want to escape.
# match single slash character below, do not escape
%r|/|
# Flag characters can be matched by the following syntax
%r[</(. *) >]i
Regular expression pattern
In addition to the control characters, (+?. * ^ $ () [] {} | \), all other characters match itself. You can escape control characters by placing a backslash before the control character.
The following table lists the regular expression syntax available in Ruby.
Search and replace
Sub and gsub and their substitution variables sub! and gsub! is a string method that is important when you use regular expressions.
All of these methods perform search and replace operations using the regular expression pattern. Sub and sub! The first occurrence of the replacement pattern, gsub and gsub! Replace all occurrences of the pattern.
Sub and Gsub return a new string, keeping the original string unmodified, while the sub! and gsub! The strings they call are modified.
Here is an example:
#!/usr/bin/ruby
phone = "2004-959-559 #This is phone number"
# remove Ruby comment
phone = phone.sub! ( /#.*$/, "")
puts "phone Num: #{phone}"
# Remove other characters other than numbers
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"
to change All "rails" to "rails"
text.gsub! (" Rails, Rails)
# change All the words "rails" to the first letter capital
text.gsub! ( /\brails\b/, "Rails")
puts "#{text}"
This will produce the following results:
Rails are rails, really good Ruby on rails