Reputation: 238717
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.
Upvotes: 10
Views: 43318
Reputation: 1094
Another way:
name = "my name is: andrew".split(/: */)[1] # => "andrew"
or
name = "my name is: andrew".split(/: */).last # => "andrew"
"my name is: andrew".split(/: */) # => ["my name is", "andrew"]
Then we select the second item:
["my name is", "andrew"][1] # => "andrew"
Upvotes: 9
Reputation: 238717
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.
original_string = "my name is: andrew"
name = original_string.sub(/^my name is: /, '') # => 'andrew'
another_format = "/nick andrew"
name = another_format.sub(/^\/nick /, '') # => 'andrew'
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 match
method:
original_string = "my name is: andrew"
matches = original_string.match /^my name is: (.*)/
name = matches[1] # return the first match
Upvotes: 7
Reputation: 65467
One way to do that is:
s = "my name is: andrew"
pos = (s =~ /(?!.*:).*/)
result = s[pos..-1]
p result.strip! # "andrew"
Another:
s = "my name is: andrew";
p s.slice(s.index(":")..-1) # "andrew"
Upvotes: 3
Reputation: 12496
s = "my name is: andrew"
p s.split(':')[1].strip # "andrew"
See
Upvotes: 15