开发者

How do you use variables in regex?

I am trying to pull from this string the photo ID : 30280 :

"--- !ruby/struct:PhotoJob \nimage_id: 30280\n"

I've seen this sort of thing 开发者_如何学JAVAdone in regex before where you can look for a couple parameters that match like /nimage_id: \d/ and then return \d.

How can I return /d or the number 30280 from that string?


What's funny is that you have a Ruby Struct there, so you could do the following and let YAML take care of the parsing.

PhotoJob = Struct.new(:image_id)
job = YAML.load("--- !ruby/struct:PhotoJob \nimage_id: 30280\n")
job.image_id
=> 30280


use group matches "--- !ruby/struct:PhotoJob \nimage_id: 30280\n".scan(/image_id: (\d+)/)[0]

>> matches = "--- !ruby/struct:PhotoJob \nimage_id: 30280\n".match(/struct:(.*) .*image_id: (\d+)/m)
=> #<MatchData "struct:PhotoJob \nimage_id: 30280" 1:"PhotoJob" 2:"30280">
>> matches[1]
=> "PhotoJob"
>> matches[2]
=> "30280"


str = "--- !ruby/struct:PhotoJob \nimage_id: 30280\n"
image_id = str.scan(/\d+/)[0]
#=> "30280"


RE = '\nimage_id: (\d+)\n'

The group defined by parentheses around \d+ catches the number

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜