【发布时间】:2009-03-17 02:47:29
【问题描述】:
鉴于此文本:
/* F004 (0309)00 */ /* 字段 1 */ /* 字段 2 */ /* F004 (0409)00 */ /* 字段 1 */ /* 字段 2 */如何将它解析成这个数组:[
["F004"],["0309"],["/* field 1 */\n/* field 2 */"],
["F004"],["0409"],["/* field 1 */\n/* field 2 */"]
]
我得到了解析前两项的代码:
form = /\/\*\s+(\w+)\s+\((\d{4})\)[0]{2}\s+\*\//m
text.scan(form)
[
["F004"],["0309"],
["F004"],["0409"]
]
这是我尝试解析所有三个并失败的代码,并出现无效的正则表达式错误:
form = /\/\*\s+(\w+)\s+\((\d{4})\)[0]{2}\s+\*\//m
form_and_fields = /#{form}(.[^#{form}]+)/m
text.scan(form_and_fields)
编辑: 多亏了rampion和singpolyma,这最终对我有用:
form = /
\/\*\s+(\w+)\s+\((\d+)\)\d+\s+\*\/ #formId & edDate
(.+?) #fieldText
(?=\/\*\s+\w+\s+\(\d+\)\d+\s+\*\/|\Z) #stop at beginning of next form
# or the end of the string
/mx
text.scan(form)
【问题讨论】: