Regular Expressions Flashcards

1
Q

What is a regular expression?

A

A regular expression is simply a way of specifying a pattern of characters to be matched in a string. In Ruby, you typically create a regular expression by writing a pattern between slash characters (/pattern/).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

=~

A

The match operator =~ can be used to match a string against a regular expression. If the pattern is found in the string, =~ returns its starting position; otherwise, it returns nil.

Example:

The following code fragment writes a message if a string contains the text Perl or Python:

if line =~ /Perl|Python/
puts “Scripting language mentioned: #{line}”
end

Example:

/cat/ =~ “dog and cat” # => 8
/cat/ =~ “catch” # => 0
/cat/ =~ “Cat” # => nil

You can put the string first:

“dog and cat” =~ /cat/ # => 8

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

[\w’]+

In Ruby / [\w’]+/

A

Matches sequences containing “word characters” and single quotes.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Which characters do not match themselves?

A
.
|
(
)
[
]
{
}
\+
\
^
$
*
?

Every other character matches itself.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How do you match a special character?

A

You use the escape character the same way you would use in a string:

Example:

“That's great.”

Example:

/*/

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

.sub

A

sub takes a pattern and some replacement text. If it finds a match for the pattern in the string, it replaces the matched substring with the replacement text. Sub only replaces the first match it finds.

str = "Dog and Cat"
new_str = str.sub(/Cat/, "Gerbil")

puts “Let’s go to the #{new_str} for a pint.”

produces:
Let’s go to the Dog and Gerbil for a pint.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

.gsub

A

gsub takes a pattern and some replacement text. If it finds a match for the pattern in the string, it replaces the matched substring with the replacement text. gsub replaces all.

str = "Dog and Cat"
new_str1 = str.sub(/a/, "*") 
new_str2 = str.gsub(/a/, "*") 

puts “Using sub: #{new_str1}”
puts “Using gsub: #{new_str2}”

produces:
Using sub: Dog *nd Cat Using gsub: Dog nd Ct

How well did you know this?
1
Not at all
2
3
4
5
Perfectly