Ruby Regular Expressions with Special Characters
In Ruby, how can I split a string such as "John Doe+123456"
so that I can have two variables with characters both before and after "+"
?
I just started with Ruby today, but I can't seem to get special characters like "+"
collaborate.
As a side note, I'm not new to programming, just Ruby.
+3
source to share
2 answers
If you already know that you always strip the same character, you can simply specify the character as a string:
> "John Doe+123456".split('+') # no regular expression needed
=> ["John Doe", "123456"]
or if you need to use a regex, then release +
with \
:
> "John Doe+123456".split(/\+/) # using a regular expression; escape the +
=> ["John Doe", "123456"]
Last but not least, here's another way to do it:
> "John Doe+123456".scan(/[^+]+/) # find all sequences of characters which are not a +
=> ["John Doe", "123456"]
+5
source to share