0
str = "cruel world"
#pattern can be /(?<a>.)(?<b>.)/ OR /(?<b>.)(?<a>.)/
#which was inputted by user, we don't know which one will be picked up by user.
pattern = params[:pattern]
請使用str.scan(/#{pattern}/)
或其它匹配方法期望輸出:如何確定命名組如果正則表達式是由用戶輸入
p a
# ["c", "u", "l", "w", "r"]
p b
# ["r", "e", " ", "o", "l"]
p c
# [ ]
# there is no named group: `?<c>` in this case. However, we should take it if user inputted.
這是我的解決方案:
str = "cruel world"
#case 1
pattern = /(?<a>.)(?<b>.)/
a = Array.new
b = Array.new
c = Array.new
str.scan(/#{pattern}/) do |x|
a << Regexp.last_match(:a) if $~.names.include? "a"
b << Regexp.last_match(:b) if $~.names.include? "b"
c << Regexp.last_match(:c) if $~.names.include? "c"
end
p a
p b
p c
有沒有更好的辦法?
謝謝。這個解決方案是否仍然覆蓋名爲'c'的情況可能存在或不存在? – 2012-03-03 15:30:07
看看測試... – 2012-03-03 18:34:39
非常感謝:D – 2012-03-03 18:56:31