写一个Regexp
并不难。自由间距模式可让您在多行上编写模式并支持注释。这是一个带有命名捕获组的示例:
string = "1 name lastname 234 washington city/NY"
pattern = /\A
(?<id>.{2}) # 2 charcters for the id
(?<name>.{20}) # 20 characters for the name
(?<zip>.{6}) # 6 characters for the zip code
(?<city>.+) # remaining characters for city and state
\Z/x
match = string.match(pattern)
#=> #<MatchData "1 name lastname 234 washington city/NY" id:"1 " name:"name lastname " zip:"234 " city:"washington city/NY">
match[:id] #=> "1 "
match[:name] #=> "name lastname "
match[:zip] #=> "234 "
match[:city] #=> "washington city/NY"