Give an example to explain the regular expressions in ruby

Time:2022-5-9

 regular expression Is a special character sequence that can help match or find other strings or strings. The pattern used maintains a special syntax.

Regular expression text is a slash between patterns or any separator%r 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:

?
1
2
3
4
5
6
7
8
9
10
11
#!/usr/bin/ruby
 
line1 = "Cats are smarter than dogs";
line2 = "Dogs also like meat";
 
if ( line1 =~ /Cats(.*)/ )
 puts "Line1 starts with Cats"
end
if ( line2 =~ /Cats(.*)/ )
 puts "Line2 starts with Dogs"
end

This will produce the following results:

?
1
Line1 starts with Cats

Regular expression modifier:

The text of a regular expression can include an optional modifier to control all aspects of matching. After modifying and specifying the second slash character, as shown above, it can be expressed as one of these characters:

Give an example to explain the regular expressions in ruby

% Q separated string is the same as text,RubyAllow regular expressions with% R followed by the selected delimiter. This is very useful when the described pattern contains forward slash characters and you do not want to escape:

?
1
2
3
4
5
# Following matches a single slash character, no escape required
%r|/|       
 
# Flag characters are allowed with this syntax, too
%r[</(.*)>]i

Regular expression pattern:

All characters match except the control characters (+?. * ^ $() [] {} |). Escape control characters can be preceded by backslashes.

Search and replace:

The most important thing about the string method is to use regular expressions sub and gsub, which are local variants of sub! And gsub!

All of these methods use a regular expression pattern during search and replace operations. sub & sub! Replace the first pattern gsub & gsub! Replace all occurrences.

sub! And gsub! Returns a new string, unmodified original sub and gsub, which are called modified strings.

The following example:

?
1
2
3
4
5
6
7
8
9
10
11
#!/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:

?
1
2
Phone Num : 2004-959-559
Phone Num : 2004959559

Here is another example:

?
1
2
3
4
5
6
7
8
9
10
11
#!/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!(/rails/, "Rails")
 
puts "#{text}"

This will produce the following results:

?
1
Rails are Rails, really good Ruby on Rails