我正在尝试匹配switch
块中的字符串。匹配和分支部分工作正常,但我需要一种方法来检索匹配上的捕获组。
有没有办法做到这一点?怎么样?
switch
when str.match /f(o+)bar/ then something # I need the capture group here
when str.match /hasta la (vista|pasta)/ then something_else # or here
答案 0 :(得分:1)
您还可以定义效用函数matching
和matches
,以使when
案例看起来更清晰:
# Definitions
match = string = null
matching = (s) ->
string = s
true
matches = (re) -> (match = re.exec string) != null
# Usage:
switch matching 'hasta la pasta'
when matches /f(o+)bar/ then console.log match
when matches /hasta la (vista|pasta)/ then console.log match
答案 1 :(得分:0)
when
语句中进行赋值,然后可以按原样使用
switch
when mtch = str.match /f(o+)bar/ then something(mtch[1].length)
when mtch = str.match /hasta la (vista|pasta)/ then something_else(mtch[0])
按预期工作,因为我可以照常在mtch
中访问匹配结果。