我有这个正则表达式^\w+-(\w+)-(\w+)-(\w+)
我在CoffeeScript中解构如下:
result = {}
[_, result.serialNumber, result.caseId, result.sequenceNumber] = /\w+-(\w+)-(\w+)-(\w+)/.exec(file.name)
但是我希望有一种更通用的方法,不事先知道对象键,而是将它们嵌入到返回的正则表达式组中,如伪代码
/\w+-(serialNumber:\w+)-(caseId:\w+)-(sequenceNumber:\w+)/.exec(file.name)
并且有一个小功能可以根据该信息创建对象。
可能的?
答案 0 :(得分:1)
通过将匹配对象分散到预定义的函数中,我可以想到保持在纯JS世界中的一种方式可能是这样的:
str = "ABC-def-hij-klm"
yieldObject = (matchData, serialNumber="", caseId="", sequenceNumber="") ->
serialNumber: serialNumber
caseId: caseId
sequenceNumber: sequenceNumber
yieldObject(str.match(/\w+-(\w+)-(\w+)-(\w+)/)...)
您还可以使用一些对象工厂来执行与this SO answer类似的操作 并使用对象理解和一些部分应用程序使该过程更适用于其他地方:
str = "ABC-def-hij-klm"
objectBuilder = (keys...)->
(matchData, matches...)->
(new -> @[k] = matches[i] for k, i in keys; @)
# yieldObject is a function ready to accept the regex
yieldObject = objectBuilder('serialNumber', 'caseId', 'sequenceNumber')
# splatting the regex makes it into an array of values
yieldObject(str.match(/\w+-(\w+)-(\w+)-(\w+)/)...) #=> Object {serialNumber: "def", caseId: "hij", sequenceNumber: "klm"}
答案 1 :(得分:1)
我希望使用 builder 函数扩展RegExp
原型:
RegExp::builder = (map...) ->
re = this
(str) -> new -> m = str.match(re)[1..]; @[field] = m.shift() for field in map; @
# Create a builder function that maps re groups to members
builder = /\w+-(\w+)-(\w+)-(\w+)/.builder("serialNumber", "caseId", "sequenceNumber")
# build as much objects as you want with the same builder:
obj = builder "ABC-def-hij-klm"
console.log obj
obj = builder "ABC-ddd-hhh-kkk"
console.log obj
产:
{ serialNumber: 'def', caseId: 'hij', sequenceNumber: 'klm' }
{ serialNumber: 'ddd', caseId: 'hhh', sequenceNumber: 'kkk' }