I have a string that looks something like this:
"my name is: andrew"
I’d like to parse the string, pull out the name from the string, and assign it to a variable. How would I do this with Ruby?
Update:
The string I used as an example was only an example. The strings that I will be working with can change formats, so you can’t rely on the colon being in the actual example. Here are a few examples that I’m working with:
"/nick andrew" # command: nick, value: "andrew"
"/join developers" # command: join, value: "developers"
"/leave" # command: leave, value: nil
I’d like to use some sort of regular expression to solve this (since the string can change formats), rather than splitting the string on certain characters or relying on a certain character position number.
This tutorial really helped me understand how to work with regular expressions in Ruby.
One way to use a regular expression to get the string you want is to replace the stuff you don’t want with an empty string.
However, that’s just string replacement/substitution. The regex is not capturing anyting.
To capture a string using a regular expression, you can use the Ruby
matchmethod: