2013-07-22 111 views
0

我在这个简单的正则表达式中遇到了最糟糕的时间。拆分字母和数字之间的空格

例输入:

Cleveland Indians 5, Boston Redsox 4 

我想在,和字母和数字之间的空间分割

输出示例:

Cleveland Indians 
5 
Boston Redsox 
4 

这里是我有什么到目前为止,但它仍然包括数字。

/,|\s[0-9]/ 
+1

如何在'分裂,然后'空间?最后的元素将是数字,第一个X将是团队的名称。这个或从空间的最后一个索引开始工作。 –

回答

4
string = "Cleveland Indians 5, Boston Redsox 4" 
string.split /,\s*|\s(?=\d)/ 
# => ["Cleveland Indians", "5", "Boston Redsox", "4"] 

\s(?=\d):一个空间,随后使用lookahead一个数字。

+1

你是一个绅士和学者。你能解释正则表达式的第二部分吗? – Franklin

+0

@Franklin对不起,我编辑了我的答案。 – oldergod

1

如果您将它分成两个分组 - 一个在逗号+空格处,然后一个将分组名称与分数分开 - 可能会更清晰一些,尤其是如果您必须添加更多选项逗号太(真实世界的数据变得混乱!):

scores = "Cleveland Indians 5, Boston Redsox 4" 
scores.split(/,\s*/).map{|score| score.split(/\s+(?=\d)/)} 
=> [["Cleveland Indians", "5"], ["Boston Redsox", "4"]] 

得到的名单列表是一个更有意义的分组了。

0
"Cleveland Indians 5, Boston Redsox 4".split(/\s*(\d+)(?:,\s+|\z)/) 
# => ["Cleveland Indians", "5", "Boston Redsox", "4"] 
0

1)

str = "Cleveland Indians 15, Boston Red Sox 4" 
phrases = str.split(", ") 

phrases.each do |phrase| 
    *team_names, score = phrase.split(" ") 
    puts team_names.join " " 
    puts score 
end 


--output:-- 
Cleveland Indians 
15 
Boston Red Sox 
4 

2)

str = "Cleveland Indians 15, Boston Red Sox 4" 

pieces = str.split(/ 
    \s*  #A space 0 or more times 
    (\d+)  #A digit 1 or more times, include match with results 
    [,\s]* #A comma or space, 0 or more times 
/x)   

puts pieces 



--output:-- 
Cleveland Indians 
15 
Boston Red Sox 
4 

第一分割的是“15”,并且第二分割是“4” - 与包含在结果中的分数。

3)

str = "Cleveland Indians 15, Boston Red Sox 4" 

str.scan(/ 
    (
     \w  #Begin with a word character 
     \D+  #followed by not a digit, 1 or more times 
    ) 
    [ ]  #followed by a space 
    (\d+)  #followed by a digit, one or more times 
/x) {|capture_groups| puts capture_groups} 


--output:-- 
Cleveland Indians 
15 
Boston Red Sox 
4 
相关问题