Regexp Flashcards

You may prefer our related Brainscape-certified flashcards:
1
Q

How to select values by a given pattern when at least 2 values exist in a row?

A

Use {2,}

“A aaaa bb c”.scan(/\w{2,}/) #=> [“aaaa”, “bb”]

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

How to return a matched string part by regexp?

A
'name 1232 name'[/\d+/]
# => 1232
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How to get captured group by name inside regexp?

A
(?Regexp)
/\$(?\d+)\.(?\d+)/.match('$3.67')[:dollars]
 # => 3
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How to send a variable to regexp?

A

ip = ‘\S+’

/#{ip}/

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

How to use regexp without explicit spaces?

A

/\w+ /x

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

How to use explicit space?

A

/\ | [ ]/

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

How to use multiline regexp?

A
%r{
  reg1
  reg2
  reg3
}x
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How to replace multiply words at the same time?

A
animals_to_replace = ["tigers", "elephants", "snakes"]
text = "In this Zoo we have tigers, elephants & snakes"

text.gsub(Regexp.union(animals_to_replace), “cats”)

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

How to increment every number in the string “a1 b2 c3”?

A

“a1 b2 c3”.gsub(/\d+/) { |number| number.next }

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

What are the differences between \A \Z and ^ $ ?

A

If you want to match strictly at the start of a string, and not just at the start of a new line (after a \n ), you need to use \A and \Z instead of ^ and $ .

“foo\nbar”.match(/^bar/) #
“foo\nbar”.match(/\Abar/) # nil

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

What is Positive lookahead assertion? And why do we need it?

A

(?=pat) - Positive lookahead assertion: ensures that the following characters match pat, but doesn’t include those characters in the matched text.
We need it to check that regexp satisfy several conditions for example we check if we have at leat one lovercase and uppercase and number.

‘fjd3IR9’.match?(/(?=.[a-z])(?=.[A-Z])(?=.*[0-9])/)

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

What is Negative lookahead assertion?

A

(?!pat) - Negative lookahead assertion: ensures that the following characters do not match pat, but doesn’t include those characters in the matched text

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