Regexp Flashcards
How to select values by a given pattern when at least 2 values exist in a row?
Use {2,}
“A aaaa bb c”.scan(/\w{2,}/) #=> [“aaaa”, “bb”]
How to return a matched string part by regexp?
'name 1232 name'[/\d+/] # => 1232
How to get captured group by name inside regexp?
(?Regexp) /\$(?\d+)\.(?\d+)/.match('$3.67')[:dollars] # => 3
How to send a variable to regexp?
ip = ‘\S+’
/#{ip}/
How to use regexp without explicit spaces?
/\w+ /x
How to use explicit space?
/\ | [ ]/
How to use multiline regexp?
%r{ reg1 reg2 reg3 }x
How to replace multiply words at the same time?
animals_to_replace = ["tigers", "elephants", "snakes"] text = "In this Zoo we have tigers, elephants & snakes"
text.gsub(Regexp.union(animals_to_replace), “cats”)
How to increment every number in the string “a1 b2 c3”?
“a1 b2 c3”.gsub(/\d+/) { |number| number.next }
What are the differences between \A \Z and ^ $ ?
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
What is Positive lookahead assertion? And why do we need it?
(?=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])/)
What is Negative lookahead assertion?
(?!pat) - Negative lookahead assertion: ensures that the following characters do not match pat, but doesn’t include those characters in the matched text