解析来自 POST 的制表符分隔文本
Parse Tab Delimited Text from POST
我有一个 API 在字段值
中向我发送制表符分隔信息
我需要将其解析为单独的字段:
Post:
"\nuserName\tpassword\tfName\tlName\tuserPhone\tcompName\tcontName\taddr1\taddr2\tcity\tstate\tpostalCode\tcountry\tphone\tfax\temail\tbusnType\tDOTNumber\tMCNumber\ntest\tabc123\tTest\tName\t(555) 555-5555\t\t\t\t\t\t\t58638\tUS\t(555) 555-5555\t(555) 555-5555\t\tTest\t12345678\tMC000000\n"
字段应匹配的内容:
userName password fName lName userPhone compName contName addr1 addr2 city state postalCode country phone fax email busnType DOTNumber MCNumber
test abc123 Test Name (555) 555-5555 58638 US (555) 555-5555 (555) 555-5555 Test 12345678 MC000000
不确定我是否必须将其写入 csv 文件然后读取,或者我是否可以按原样读取。或者如何去做。
最简单的方法是使用 Ruby 的 CSV 标准库:
require 'csv'
s = "\nuserName\tpassword\tfName\tlName\tuserPhone\tcompName\tcontName\taddr1\taddr2\tcity\tstate\tpostalCode\tcountry\tphone\tfax\temail\tbusnType\tDOTNumber\tMCNumber\ntest\tabc123\tTest\tName\t(555) 555-5555\t\t\t\t\t\t\t58638\tUS\t(555) 555-5555\t(555) 555-5555\t\tTest\t12345678\tMC000000\n"
csv = CSV.new(s, col_sep: "\t")
csv.each do |row|
puts row.inspect
end
输出为:
[]
["userName", "password", "fName", "lName", "userPhone", "compName", "contName", "addr1", "addr2", "city", "state", "postalCode", "country", "phone", "fax", "email", "busnType", "DOTNumber", "MCNumber"]
["test", "abc123", "Test", "Name", "(555) 555-5555", nil, nil, nil, nil, nil, nil, "58638", "US", "(555) 555-5555", "(555) 555-5555", nil, "Test", "12345678", "MC000000"]
我有一个 API 在字段值
中向我发送制表符分隔信息我需要将其解析为单独的字段:
Post:
"\nuserName\tpassword\tfName\tlName\tuserPhone\tcompName\tcontName\taddr1\taddr2\tcity\tstate\tpostalCode\tcountry\tphone\tfax\temail\tbusnType\tDOTNumber\tMCNumber\ntest\tabc123\tTest\tName\t(555) 555-5555\t\t\t\t\t\t\t58638\tUS\t(555) 555-5555\t(555) 555-5555\t\tTest\t12345678\tMC000000\n"
字段应匹配的内容:
userName password fName lName userPhone compName contName addr1 addr2 city state postalCode country phone fax email busnType DOTNumber MCNumber
test abc123 Test Name (555) 555-5555 58638 US (555) 555-5555 (555) 555-5555 Test 12345678 MC000000
不确定我是否必须将其写入 csv 文件然后读取,或者我是否可以按原样读取。或者如何去做。
最简单的方法是使用 Ruby 的 CSV 标准库:
require 'csv'
s = "\nuserName\tpassword\tfName\tlName\tuserPhone\tcompName\tcontName\taddr1\taddr2\tcity\tstate\tpostalCode\tcountry\tphone\tfax\temail\tbusnType\tDOTNumber\tMCNumber\ntest\tabc123\tTest\tName\t(555) 555-5555\t\t\t\t\t\t\t58638\tUS\t(555) 555-5555\t(555) 555-5555\t\tTest\t12345678\tMC000000\n"
csv = CSV.new(s, col_sep: "\t")
csv.each do |row|
puts row.inspect
end
输出为:
[]
["userName", "password", "fName", "lName", "userPhone", "compName", "contName", "addr1", "addr2", "city", "state", "postalCode", "country", "phone", "fax", "email", "busnType", "DOTNumber", "MCNumber"]
["test", "abc123", "Test", "Name", "(555) 555-5555", nil, nil, nil, nil, nil, nil, "58638", "US", "(555) 555-5555", "(555) 555-5555", nil, "Test", "12345678", "MC000000"]