在switch语句中捕获组

时间:2017-03-03 18:54:07

标签: javascript regex coffeescript 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

2 个答案:

答案 0 :(得分:1)

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

答案 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中访问匹配结果。