简体   繁体   中英

How to extract words from string in ruby

I want to extract words from string in ruby.

For example, I have a url string "......../default/d1235sf3/......" .

I want to extract "d1235sf3" from it. I am thinking using regex, but I don't know the grammar. Can anyone help me? Thanks!

Use string.match with regex and isolate groups:

string = "http://test.com/something/default/d1235sf3/"
string.match("^.*\/default\/(.*)\/")

Notice how I structured my regex, isolating the part you are interested in with ().

NOTE: Regular expressions (regex) are a huge, marvelous and interesting subject which will help you in situations like this when you have to "match" text to a certain "mold", but I really can't go in depth here. This tutorial site seems pretty good, so you should get a refresher on how to use regex here: http://regexone.com/

string.match will produce a MatchData object with attributes corresponding to its matching groups:

=> #<MatchData "http://test.com/something/default/d1235sf3/" 1:"d1235sf3">

Notice how attribute 1 has the little bit of information that you want. Right after calling string.match , you can use the special variable $1 in ruby to access the info that you want:

2.0.0-p643 :004 > $1
 => "d1235sf3" 
2.0.0-p643 :005 > info = $1
 => "d1235sf3" 
2.0.0-p643 :006 > info
 => "d1235sf3" 
string = "......../default/d1235sf3/......"
string[%r{/default/([^/]*)/}, 1]
# => "d1235sf3"

A short alternative to Alfredo's answer - this form of regexp ( string[regexp] or string[regexp, group] ) is well-suited to extracting a particular part of a string; using %r{...} instead of /.../ is good to avoid having to escape slashes.

> string = "......../default/d1235sf3/......"
> string.split('/default/').last.split('/')[0]
#=> "d1235sf3" 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM