ruby将字符串拆分成多个固定长度的字符串

时间:2013-10-27 23:25:05

标签: ruby regex string

我想知道是否可以将字符串拆分为多个不同长度的分区。我想拆分这个字符串,例如:

string = "1 name lastname       234   washington city/NY"

分为四个子字符串,其中:

  • 第一个分区有前2个字符("1 "
  • 第二个分区到 有后续的15个字符("name lastname "
  • 第3个分区 后续的6个字符("234 "
  • 第4个分区 后续的20个字符("washington city/NY"

2 个答案:

答案 0 :(得分:2)

你只需索引编写:

string[0,2]
string[4,15]
stirng[20,6]
string[27,20]

答案 1 :(得分:0)

写一个Regexp并不难。 free-spacing mode允许您在多行上编写模式并支持注释。以下是命名捕获组的示例:

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"