如何使用正则表达式将以下字符串拆分为两个变量?有时从歌曲位置到标题的空间会丢失,例如2.Culture Beat – Mr. Vain
2. Culture Beat – Mr. Vain
我正在寻找的结果:
pos = 2
title = Culture Beat – Mr. Vain
尝试这个:
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
像这样?
(full, pos, title) = your_string.match(/(\d+)\.\s*(.*)/).to_a
捕获组的一种选择:
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'"