An example is provided to explain the regular expressions in Ruby and the regular expressions in ruby.
A regular expression is a special character sequence that can help match or find other strings or strings. The pattern used maintains a special syntax.
The regular expression text is a slash between a pattern or any separator % r is as follows:
Syntax:
Copy codeThe Code is as follows:/pattern/
/Pattern/im # option can be specified
% R! /Usr/local! # General delimited regular expression
For example:
#!/usr/bin/rubyline1 = "Cats are smarter than dogs";line2 = "Dogs also like meat";if ( line1 =~ /Cats(.*)/ ) puts "Line1 starts with Cats"endif ( line2 =~ /Cats(.*)/ ) puts "Line2 starts with Dogs"end
This produces the following results:
Line1 starts with Cats
Regular Expression modifier:
The text of a regular expression can include an optional modifier to control the matching in various aspects. After the second slash character is modified, as shown in the preceding figure, it can be expressed as one of these characters:
The % Q separator is the same as the string text. Ruby allows the regular expression to contain % r, and then the selected delimiters. This is very useful. When the described mode contains the forward slash character, you do not want to escape it:
# Following matches a single slash character, no escape required%r|/| # Flag characters are allowed with this syntax, too%r[</(.*)>]i
Regular Expression mode:
Except the control characters, (+? . * ^ $ () [] {}| \), All characters match. Escape control characters can be preceded by a backslash.
Search and replace:
The most important thing about the String method is to use the regular expressions sub and gsub. They are local variants sub! And gsub!
All these methods use a regular expression pattern during the search and replacement operations. Sub & sub! Replace the first occurrence mode gsub & gsub! Replace all occurrences.
Sub! And gsub! Returns a new string. unmodified original sub and gsub are called modified strings.
The following example:
#!/usr/bin/rubyphone = "2004-959-559 #This is Phone Number"# Delete Ruby-style commentsphone = phone.sub!(/#.*$/, "") puts "Phone Num : #{phone}"# Remove anything other than digitsphone = phone.gsub!(/\D/, "") puts "Phone Num : #{phone}"
This produces the following results:
Phone Num : 2004-959-559Phone Num : 2004959559
The following is another example:
#!/usr/bin/rubytext = "rails are rails, really good Ruby on Rails"# Change "rails" to "Rails" throughouttext.gsub!("rails", "Rails")# Capitalize the word "Rails" throughouttext.gsub!(/\brails\b/, "Rails")puts "#{text}"
This produces the following results:
Rails are Rails, really good Ruby on Rails