2013-04-15 29 views
-1

如何使用正则表达式将以下字符串拆分为两个变量?有时,从乐曲位置标题的空间缺少如2.Culture Beat – Mr. Vain将“123.一些字符串”匹配成两个变量

2. Culture Beat – Mr. Vain 

结果我要找:

pos = 2 
title = Culture Beat – Mr. Vain 
+1

要匹配一系列的1个或多个数字,文字句点,一系列的0或更多的空间,然后剩下的所有字符。你应该能够分解这个问题并弄清楚。这是一个非常微不足道的正则表达式。 – meagar

+0

您可以包含迄今为止尝试过的正则表达式吗? – Stefan

+0

与正则表达式玩了几个小时,没有得到任何地方。下面的两个例子都有效 – atmorell

回答

2

是否这样?

(full, pos, title) = your_string.match(/(\d+)\.\s*(.*)/).to_a 
2

试试这个:

s = "2. Culture Beat – Mr. Vain" 

# split the string into an array, dividing by point and 0 to n spaces 
pos, title = s.split(/(?!\d+)\.\s*/) 

# coerce the position to an integer 
pos = pos.to_i 
1

一个与捕获组选项:

match = "2. Culture Beat - Mr. Vain".match(/(?<position>\d+)\.\s*(?<title>.*)/) 

position = match['position'] 
title = match['title'] 

p "Position: #{ position }; Title: '#{ title }'" 
# => "Position: 2; Title: 'Culture Beat - Mr. Vain'" 
相关问题