Ruby: how to parse a string to pull something and assign it to a variable

I have a line that looks something like this:

"my name is: andrew" 

I would like to parse a string, pull the name out of the string and assign it to a variable. How do I do this with Ruby?

Update:

The line I used as an example was just an example. The lines that I will work with can change formats, so you cannot rely on the colon in the actual example. Here are some examples I work with:

 "/nick andrew" # command: nick, value: "andrew" "/join developers" # command: join, value: "developers" "/leave" # command: leave, value: nil 

I would like to use some kind of regular expression to solve this problem (since a string can change formats), and not split the string into specific characters or rely on a specific character position number.

+6
source share
5 answers

This tutorial really helped me understand how to work with regular expressions in Ruby.

One way to use a regular expression to get the right string is to replace the unnecessary content 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, this is just a replacement / replacement string. A regular expression does not commit 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 
+5
source
 s = "my name is: andrew" p s.split(':')[1].strip # "andrew" 

Cm

+12
source

Another way:

 name = "my name is: andrew".split(/: */)[1] # => "andrew" 

or name = "my name: andrew" .split (/: * /). last # => "andrew"


Breaking it, first we break it into pieces. The regular expression /: * / says a: followed by any number of spaces, there will be our delimiter.

 "my name is: andrew".split(/: */) # => ["my name is", "andrew"] 

Then we select the second element:

 ["my name is", "andrew"][1] # => "andrew" 
+5
source

One way to do this:

 s = "my name is: andrew" pos = (s =~ /(?!.*:).*/) result = s[pos..-1] p result.strip! # "andrew" 

Other:

 s = "my name is: andrew"; p s.slice(s.index(":")..-1) # "andrew" 
+2
source
 s.split.last 

This should work with all your cases.

+1
source

Source: https://habr.com/ru/post/900794/


All Articles