【发布时间】:2015-06-29 13:08:48
【问题描述】:
我在 GNU Smalltalk 3.2.5 中有一个尝试对键值设置进行分组匹配的简单示例:
st> m := 'a=b' =~ '(.*?)=(.*)'
MatchingRegexResults:'a=b'('a','b')
上面的示例按预期工作。但是,如果没有匹配到第二组(.*),则会产生异常:
st> m := 'a=' =~ '(.*?)=(.*)'
Object: Interval new "<-0x4ce2bdf0>" error: Invalid index 1: index out of range
SystemExceptions.IndexOutOfRange(Exception)>>signal (ExcHandling.st:254)
SystemExceptions.IndexOutOfRange class>>signalOn:withIndex: (SysExcept.st:660)
Interval>>first (Interval.st:245)
Kernel.MatchingRegexResults>>at: (Regex.st:382)
Kernel.MatchingRegexResults>>printOn: (Regex.st:305)
Kernel.MatchingRegexResults(Object)>>printString (Object.st:534)
Kernel.MatchingRegexResults(Object)>>printNl (Object.st:571)
我不明白这种行为。我本来希望结果是('a', nil),而m at: 2 是nil。我尝试了以下不同的方法:
st> 'a=' =~ '(.*?)=(.*)' ifMatched: [ :m | 'foo' printNl ]
'foo'
'foo'
这可以正确确定与正则表达式匹配。但是我仍然无法检查特定组是否为nil:
st> 'a=' =~ '(.*?)=(.*)' ifMatched: [ :m | (m at: 2) ifNotNil: [ (m at: 2) printNl ] ]
Object: Interval new "<-0x4ce81b58>" error: Invalid index 1: index out of range
SystemExceptions.IndexOutOfRange(Exception)>>signal (ExcHandling.st:254)
SystemExceptions.IndexOutOfRange class>>signalOn:withIndex: (SysExcept.st:660)
Interval>>first (Interval.st:245)
Kernel.MatchingRegexResults>>at: (Regex.st:382)
optimized [] in UndefinedObject>>executeStatements (a String:1)
Kernel.MatchingRegexResults>>ifNotMatched:ifMatched: (Regex.st:322)
Kernel.MatchingRegexResults(RegexResults)>>ifMatched: (Regex.st:188)
UndefinedObject>>executeStatements (a String:1)
nil
st>
我不明白这种行为。我本来希望结果是('a', nil),而m at: 2 是nil。至少这是它在我使用过正则表达式的任何其他语言中的工作方式。这让我觉得我的语法可能不正确。
我的问题是:我是否有正确的语法来尝试匹配这样的 ASCII 键值对(例如,在解析环境设置中)?如果我这样做了,为什么会生成异常,或者有什么方法可以让它提供一个我可以在不生成异常的情况下检查的结果?
我发现自 2013 年 12 月在 gnu.org 上报告的 related issue 没有任何回复。
【问题讨论】:
标签: regex smalltalk gnu-smalltalk