我想知道是否可以将字符串拆分为多个不同长度的分区。我想拆分这个字符串,例如:
string = "1 name lastname 234 washington city/NY"
分成四个子字符串,其中:
- 第一个分区有 1st 2 个字符 (
"1 ") - 第二个分区有后续 15 个字符 (
"name lastname ") - 第三个分区有后续 6 个字符 (
"234 ") - 第 4 个分区有后续 20 个字符 (
"washington city/NY")
你只需通过索引来做到这一点:
string[0,2]
string[4,15]
stirng[20,6]
string[27,20]
写一个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"