在 switch 语句中捕获组

Capture groups in switch statement

我正在尝试匹配 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

我早该知道的。可以在 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 中访问比赛结果。

您还可以定义效用函数 matchingmatches 以使 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