开发者

How do I match a 10 character sub-string starting with 'H' in a longer string with Ruby?

I have the following string:

/Users/patelc75/Documents/code/haloror/dialup/H200000787_1313406125/H200000787_1313389058_1.xml

In开发者_如何转开发 Ruby, how do I extract the first 10 character substring that starts with the letter H and contains 9 digits (digits only) after the H. In this above example, the substring would be H200000787


String#[] method is what you need:

str = '/Users/patelc75/Documents/code/haloror/dialup/H200000787_1313406125/H200000787_1313389058_1.xml'

puts str[/H\d{9}/]     #=> H200000787


irb(main):001:0> s = "/Users/patelc75/Documents/code/haloror/dialup/H200000787_1313406125/H200000787_1313389058_1.xml"
=> "/Users/patelc75/Documents/code/haloror/dialup/H200000787_1313406125/H200000787_1313389058_1.xml"
irb(main):002:0> s =~ /H\d{9}/
=> 46
irb(main):003:0> $&
=> "H200000787"
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜