在正则表达式替换中捕获字符串

时间:2016-05-24 01:40:31

标签: regex smalltalk pharo

从我可以从正则表达式的Pharo文档中收集的内容中,我可以定义一个正则表达式对象,例如:

re := '(foo|re)bar' asRegex

我可以用以下字符串替换匹配的正则表达式:

re copy: 'foobar blah rebar' replacingMatchesWith: 'meh'

这将导致:''meh blah meh'。

到目前为止,这么好。但我想替换'bar'并单独留下前缀。因此,我需要一个变量来处理捕获的括号:

re copy: 'foobar blah rebar' replacingMatchesWith: '%1meh'

我想要结果:'foomeh blah remeh'。但是,这只是给了我:'%1meh blah %1meh'。我还尝试使用\1\\1$1{1}并获得了文字字符串替换,例如,{{1}结果。

我可以在GNU Smalltalk中轻松地执行此操作:

'\1meh blah \1meh'

但我在Pharo正则表达式文档中找不到任何告诉我如何在Pharo中执行此操作的文档。我也为Pharo正则表达式做过一堆谷歌搜索,但没有发现任何东西。这个功能是RxMatcher类还是其他Pharo正则表达式类的一部分?

2 个答案:

答案 0 :(得分:1)

在使用RxMatcher类进行实验后,我对RxMatcher#copyStream:to:replacingMatchesWith:选择器进行了以下修改:

copyStream: aStream to: writeStream replacingMatchesWith: aString
    "Copy the contents of <aStream> on the <writeStream>,
     except for the matches. Replace each match with <aString>."

    | searchStart matchStart matchEnd |
    stream := aStream.
    markerPositions := nil.
    [searchStart := aStream position.
    self proceedSearchingStream: aStream] whileTrue: [ | ws rep |
        matchStart := (self subBeginning: 1) first.
        matchEnd := (self subEnd: 1) first.
        aStream position: searchStart.
        searchStart to: matchStart - 1 do:
            [:ignoredPos | writeStream nextPut: aStream next].

        "------- The following lines replaced: writeStream nextPutAll: aString ------"
        "Do the regex replacement including lookback substitutions"
        writeStream nextPutAll: (aString format: self subexpressionStrings).
        "-------"

        aStream position: matchEnd.
        "Be extra careful about successful matches which consume no input.
        After those, make sure to advance or finish if already at end."
        matchEnd = searchStart ifTrue: 
            [aStream atEnd
                ifTrue: [^self "rest after end of whileTrue: block is a no-op if atEnd"]
                ifFalse:    [writeStream nextPut: aStream next]]].
    aStream position: searchStart.
    [aStream atEnd] whileFalse: [writeStream nextPut: aStream next]

然后“访问”类别:

subexpressionStrings
   "Create an array of lookback strings"
   | ws |
   ws := Array new writeStream.
   2 to: (self subexpressionCount) do: [ :n | | se |
      ws nextPut: ((se := self subexpression: n) ifNil: [ '' ] ifNotNil: [ se ]) ].
   ^ws contents.

通过这个修改,我可以使用Smalltalk String#format:模式对替换字符串进行回顾:

re := '((foo|re)ba(r|m))' asRegex
re copy: 'foobar meh rebam' replacingMatchesWith: '{2}bu{3} (was {1})'

结果:

'foobur (was foobar) meh rebum (was rebam)'

答案 1 :(得分:0)

你检查了Regex的帮助吗?没有#replacingAllRegex:,但匹配器有#subexpression: