2013-04-15 32 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'" 
相關問題