Reputation: 850
I was playing with Ruby's Regexp. I supposed find a Regexp trick, but I can't understand, why?
p a = "This is a test!".gsub!(//,'X')
Output of above is
"XTXhXiXsX XiXsX XaX XtXeXsXtX!X"
It puts 'X' after and before any character in the test string. Anyone knows why?
Upvotes: 1
Views: 90
Reputation: 15284
You asked it to match an empty space, so it matches every null space between letters.
It does not match a letter so all the letters remained.
Upvotes: 0
Reputation: 10662
You asked it to match a zero-width string (//
), and replace it with 'X', so it did that. gsub
scans the string and replaces every match (every letter boundary) with the replacement.
Upvotes: 2
Reputation: 168081
//
matches substrings with zero width, i.e., empty strings. There are arbitrarily many empty strings in between any adjacent characters, but the gsub
family does not keep matching at the same location. If it finds a match (i.e., the empty string in this case), then it will not match again at the same position, so it goes on to the empty string that is in between the next adjacent characters.
Upvotes: 3