如何拆分字符串而不在数组中插入空字符串 [英] How to split a string without getting an empty string inserted in the array

查看:53
本文介绍了如何拆分字符串而不在数组中插入空字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设存在匹配,我在使用正则表达式从字符串中拆分字符时遇到问题.

I'm having trouble splitting a character from a string using a regular expression, assuming there is a match.

假设下一个字符是一个或多个数字,后跟可选的空格字符,然后是我拥有的数组中的一个字符串,我想从字符串的第一部分中分离出m"或f"字符.

I want to split off either an "m" or an "f" character from the first part of a string assuming the next character is one or more numbers followed by optional space characters, followed by a string from an array I have.

我试过了:

2.4.0 :006 > MY_SEPARATOR_TOKENS = ["-", " to "]
 => ["-", " to "] 
2.4.0 :008 > str = "M14-19"
 => "M14-19" 
2.4.0 :011 > str.split(/^(m|f)\d+[[:space:]]*#{Regexp.union(MY_SEPARATOR_TOKENS)}/i)
 => ["", "M", "19"] 

注意数组开头的无关"元素,还要注意最后一个表达式只是19",而我想要字符串中的其他所有内容(14-19").

Notice the extraneous "" element at the beginning of my array and also notice that the last expression is just "19" whereas I would want everything else in the string ("14-19").

如何调整我的正则表达式,以便只有表达式中被拆分的部分最终出现在数组中?

How do I adjust my regular expression so that only the parts of the expression that get split end up in the array?

推荐答案

如果得到匹配,空元素将一直存在,因为捕获的部分出现在字符串的开头和字符串开头之间的字符串并将匹配项添加到结果数组中,无论是空字符串还是非空字符串.一旦你得到匹配,要么 shift/drop 它,或者只是删除所有空数组元素 .reject { |c|c.空?}(参见如何从一个数组?).

The empty element will always be there if you get a match, because the captured part appears at the beginning of the string and the string between the start of the string and the match is added to the resulting array, be it an empty or non-empty string. Either shift/drop it once you get a match, or just remove all empty array elements with .reject { |c| c.empty? } (see How do I remove blank elements from an array?).

然后,14-\d+[[:space:]]... 模式部分吃掉(消耗) - 把它放入一个 (?=...) 前瞻,只会检查模式匹配,但不会消耗字符.

Then, 14- is eaten up (consumed) by the \d+[[:space:]]... pattern part - put it into a (?=...) lookahead that will just check for the pattern match, but won't consume the characters.

使用类似的东西

MY_SEPARATOR_TOKENS = ["-", " to "]
s = "M14-19"
puts s.split(/^(m|f)(?=\d+[[:space:]]*#{Regexp.union(MY_SEPARATOR_TOKENS)})/i).drop(1)
#=> ["M", "14-19"]

参见 Ruby 演示

这篇关于如何拆分字符串而不在数组中插入空字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆