开发者

Matching and returning value using wildcard with regex in Ruby

Let's say I have a sting with a number of words separated by spaces. Each word has a single digit number after it. If I have a word, is it possible to find the word in t开发者_如何转开发he string and return it along with the number after it? (using Ruby)

For example:

string = "test0 chance1 already0 again4"
word = "chance"

How can I get a return value of "chance1"?

Update:

/word\d+/.match(string) returns "chance1"

This seems to be working.


Your sample and update don't work:

Update:

/string\d+/.match(word) returns "chance1"
This seems to be working.

Dumping it into irb shows:

>> string = "test0 chance1 already0 again4" #=> "test0 chance1 already0 again4"
>> word = "chance" #=> "chance"
>> /string\d+/.match(word) #=> nil

so that isn't working.

I'd recommend:

>> Hash[*string.scan(/(\w+)(\d)/).flatten]['chance'] #=> "1"

or

>> hash = Hash[*string.scan(/(\w+)(\d)/).flatten]
>> hash['chance'] #=> "1"
>> hash['test'] #=> "0"
>> hash['again'] #=> "4"

It works by scanning for the words ending with a digit, and grabbing the word and the digit separately. String.scan will return an array of arrays, where each inner array contains the groups matched.

>> string.scan(/(\w+)(\d)/) #=> [["test", "0"], ["chance", "1"], ["already", "0"], ["again", "4"]]

Then I flatten it to get a list of words followed by their matching digit

>> string.scan(/(\w+)(\d)/).flatten #=> ["test", "0", "chance", "1", "already", "0", "again", "4"]

and turn it into a hash.

>> Hash[*string.scan(/(\w+)(\d)/).flatten] #=> {"test"=>"0", "chance"=>"1", "already"=>"0", "again"=>"4"}

Then it's a simple case of asking the hash for the value that matches a particular word.

String.scan is powerful but often overlooked. For Perl programmers it's similar to using the m//g pattern match.

Here's a little different way to populate the hash:

>> string.scan(/(\w+)(\d)/).inject({}){|h,a| h[a[0]]=a[1]; h} #=> {"test"=>"0", "chance"=>"1", "already"=>"0", "again"=>"4"}


Split the string into words, then find which one includes the target word.

string.split(' ').find {|s| s.index word}


result = string.match Regexp.new(word + '\d')

This concatenates word with \d(the regexp for a single digit) which in your case would compile to /chance\d/, which would match the word 'chance' with any single digit after it. Then it would check the string for a match, so you'd get the 'chance1' in the string.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜