如何将字符串拆分为数组

时间:2014-09-08 07:19:23

标签: ruby string split

这是我带有值的示例字符串。

示例字符串: -

str = "2014-09-04 21:12:05" "5469687123030383463" "192.168.1.2" "4" "7879" "0" "43" "http://www.google.com" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36" "404" "123" "F" "21549" "50" "0" "-" "-" "Test1":"T" "Test2":"T" "Test3":"F" "Test4":"T" "Test5":"F" "Test6":"T" "Test7":"F" 

如果我使用空格分割: -

Use str.split(' ')

结果是: -

["\"2014-09-04", "21:12:05\"", "\"5469687123030383463\"", "\"192.168.1.2\"", "\"4\"", "\"7879\"", "\"0\"", "\"43\"", "\"http://www.google.com\"", "\"Mozilla/5.0", "(X11;", "Linux", "x86_64)", "AppleWebKit/537.36", "(KHTML,", "like", "Gecko)", "Chrome/35.0.1916.153", "Safari/537.36\"", "\"404\"", "\"123\"", "\"F\"", "\"21549\"", "\"50\"", "\"0\"", "\"-\"", "\"-\"", "\"Test1\":\"T\"", "\"Test2\":\"T\"", "\"Test3\":\"F\"", "\"Test4\":\"T\"", "\"Test5\":\"F\"", "\"Test6\":\"T\"", "\"Test7\":\"F\""] 

但我需要如下: -

预期结果: -

["\"2014-09-04 21:12:05\"", "\"5469687123030383463\"", "\"192.168.1.2\"", "\"4\"", "\"7879\"", "\"0\"", "\"43\"", "\"http://www.google.com\"", "\"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36\"", "\"404\"", "\"123\"", "\"F\"", "\"21549\"", "\"50\"", "\"0\"", "\"-\"", "\"-\"", "\"Test1\":\"T\"", "\"Test2\":\"T\"", "\"Test3\":\"F\"", "\"Test4\":\"T\"", "\"Test5\":\"F\"", "\"Test6\":\"T\"", "\"Test7\":\"F\""] 

我如何在ruby中实现预期的结果。

1 个答案:

答案 0 :(得分:2)

假设你的字符串是:

str = '"2014-09-04 21:12:05" "5469687123030383463" "192.168.1.2" "4" "7879" "0" "43" "http://www.google.com" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36" "404" "123" "F" "21549" "50" "0" "-" "-" "Test1":"T" "Test2":"T" "Test3":"F" "Test4":"T" "Test5":"F" "Test6":"T" "Test7":"F"'

您可以使用具有正向前瞻/后瞻断言的正则表达式来匹配由引号括起的空格(不捕获引号):

str.split(/(?<=") (?=")/)
#=> ["\"2014-09-04 21:12:05\"",
#    "\"5469687123030383463\"",
#    "\"192.168.1.2\"",
#    "\"4\"",
#    "\"7879\"",
#    "\"0\"",
#    "\"43\"",
#    "\"http://www.google.com\"",
#    "\"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36\"",
#    "\"404\"",
#    "\"123\"",
#    "\"F\"",
#    "\"21549\"",
#    "\"50\"",
#    "\"0\"",
#    "\"-\"",
#    "\"-\"",
#    "\"Test1\":\"T\"",
#    "\"Test2\":\"T\"",
#    "\"Test3\":\"F\"",
#    "\"Test4\":\"T\"",
#    "\"Test5\":\"F\"",
#    "\"Test6\":\"T\"",
#    "\"Test7\":\"F\""]