使用REGEX解析序列化数据

使用REGEX解析序列化数据,regex,activerecord,ruby-on-rails-4,Regex,Activerecord,Ruby On Rails 4,我知道了序列化的错误。。。现在我得付钱了。在我的数据库中,我有字符串属性如下所示的记录: “0 0”\n-0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n-0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

我知道了序列化的错误。。。现在我得付钱了。在我的数据库中,我有字符串属性如下所示的记录:

“0 0”\n-0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n-0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n-0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n-\n-0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n-\ \n-\n--0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n-\n-0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n-\n-\n-0 0 n-“0”\n“

有没有一种简单的方法可以只解析出里面的两个项目?在这种情况下,物品是帐篷和睡垫,但请注意,在这些长串中,可以隐藏任意数量的物品


仅供参考,这是RubyonRails 4。

使用此条目,您需要以下字符串来提取这些单词

(?<=^|\\n-\s)([\p{L} ]+?)(?=\\n)

(?好的,对不起,我无意冒犯任何人,但我真的一点都不懂正则表达式,所以我不确定代码行放在哪里。不过我最终使用了纯ruby的方式,只是:

long_string = "---\n- '0'\n- Tent\n- '0'\n- '0'\n- Sleeping pad\n- '0'\n- '0'\n- '0'\n- '0'\n- '0'\n- '0'\n- '0'\n- '0'\n- '0'\n- '0'\n- '0'\n- '0'\n- '0'\n- '0'\n- '0'\n- '0'\n- '0'\n- '0'\n- '0'\n- '0'\n- '0'\n- '0'\n- '0'\n- '0'\n- '0'\n- '0'\n- '0'\n"
new_array = long_string.split("\n- ")
#mimic what the serialization function does, which is splitting up each of the items with the "\n- " thing

new_array.select! { |t| ("A".."Z").include? t[0] }
#select only elements of the newly created array where the first character is a capital letter, since it works out that all my items would start with a capital letter

这种情况下的输出是
=>[“帐篷”、“睡垫”]

您期望的输出是什么?输入是您提供的字符串,输出是“帐篷睡垫”或者什么?理想情况下,我希望输出是
帐篷、睡垫、下一个项目等等,这样我可以转换成一个数组,然后可以在它上面运行一个枚举。嗨,对不起,我该如何使用它呢?一旦我将
项目作为一个对象?我尝试了
项目。拆分…
,但这似乎需要更多信息。谢谢!我不知道我们可以使用Ruby正则表达式,但这可能会有所帮助:它几乎与他的第二个正则表达式相同(除了在开始?:)中添加的非捕获组),并且它可以工作。不要忘记进行全局匹配。哦,在这里也测试了它,我编辑的正则表达式可以找到这两个单词(将你的字符串和我编辑的正则表达式放入)谢谢你给我介绍了这个工具!我得用它了
long_string = "---\n- '0'\n- Tent\n- '0'\n- '0'\n- Sleeping pad\n- '0'\n- '0'\n- '0'\n- '0'\n- '0'\n- '0'\n- '0'\n- '0'\n- '0'\n- '0'\n- '0'\n- '0'\n- '0'\n- '0'\n- '0'\n- '0'\n- '0'\n- '0'\n- '0'\n- '0'\n- '0'\n- '0'\n- '0'\n- '0'\n- '0'\n- '0'\n- '0'\n"
new_array = long_string.split("\n- ")
#mimic what the serialization function does, which is splitting up each of the items with the "\n- " thing

new_array.select! { |t| ("A".."Z").include? t[0] }
#select only elements of the newly created array where the first character is a capital letter, since it works out that all my items would start with a capital letter