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


Unless you literally mean the last character of the string before +

and the first immediately after it, splitting a string in ruby ​​is easy with a method .split

that takes a delimiter as an argument.



> string = "John Doe+123456"
> string.split('+')
=> ["John Doe", "123456"]

      

+3


source







All Articles