简体   繁体   English

禁止在Ruby的String#split中使用分隔符

[英]Suppress delimiters in Ruby's String#split

I'm importing data from old spreadsheets into a database using rails. 我正在使用Rails将数据从旧的电子表格导入数据库。

I have one column that contains a list on each row, that are sometimes formatted as 我有一列包含每一行的列表,有时将其格式化为

first, second

and other times like this 还有其他的时间

third and fourth

So I wanted to split up this string into an array, delimiting either with a comma or with the word "and". 因此,我想将此字符串拆分为一个数组,用逗号或单词“ and”定界。 I tried 我试过了

my_string.split /\s?(\,|and)\s?/

Unfortunately, as the docs say: 不幸的是,正如文档所说:

If pattern contains groups, the respective matches will be returned in the array as well. 如果pattern包含组,则各自的匹配项也将在数组中返回。

Which means that I get back an array that looks like 这意味着我得到了一个看起来像

[
[0] "first"
[1] ", "
[2] "second"
]

Obviously only the zeroth and second elements are useful to me. 显然,只有第零和第二个元素对我有用。 What do you recommend as the neatest way of achieving what I'm trying to do? 您推荐什么作为实现我正在尝试的最简洁的方法?

You can instruct the regexp to not capture the group using ?: . 您可以使用?:指示正则表达式不捕获组。

my_string.split(/\s?(?:\,|and)\s?/)
# => ["first", "second"] 

As an aside note 顺便一提

into a database using rails . 使用rails进入数据库。

Please note this has nothing to do with Rails, that's Ruby. 请注意,这与Rails无关,那就是Ruby。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM