如何使用正则表达式将以下字符串拆分为两个变量?有时,从歌曲位置到标题的空间缺失,例如2.Culture Beat – Mr. Vain
2. Culture Beat – Mr. Vain
结果我正在寻找:
pos = 2
title = Culture Beat – Mr. Vain
答案 0 :(得分:2)
答案 1 :(得分:2)
喜欢这个吗?
(full, pos, title) = your_string.match(/(\d+)\.\s*(.*)/).to_a
答案 2 :(得分: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
答案 3 :(得分: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'"