在Julia中替换为捕获的组

tib*_*ibL 3 regex julia

我正在尝试使用replacedoc指定的函数

replace(string :: AbstractString,pat,r [,n :: Integer = 0])

搜索给定的模式pat,并用r替换每个匹配项.如果提供n,则最多替换n次.与搜索一样,第二个参数可以是单个字符,向量或一组字符,字符串或正则表达式.如果r是一个函数,则每次出现都被替换为r(s),其中s是匹配的子字符串.如果pat是正则表达式而r是SubstitutionString,则r中的捕获组引用将替换为相应的匹配文本.

我不明白最后一句,但找不到SubstitutionString(SubString虽然有,但我也无法直接找到doc).我想在r使用所示的捕获组进行替换pat.与Python中的以下简单示例相对应的东西:

regex.sub(r'#(.+?)#', r"captured:\1", "hello #target# bye #target2#")
Run Code Online (Sandbox Code Playgroud)

返回'hello captured:target bye captured:target2'.

nic*_*y12 8

A SubstitutionString可以通过创建s"".与你如何创建正则表达式类似r"".

我想这就是你要找的东西:

julia> replace("hello #target# bye #target2#",  r"#(.+?)#", s"captured:\1")
"hello captured:target bye captured:target2"
Run Code Online (Sandbox Code Playgroud)

如果你substitution stringhttps://docs.julialang.org/en/stable/manual/strings/中搜索,你会在那里找到另一个例子.

  • 这里的文档肯定需要改进。至少,`SubstitutionString` 应该有一个文档字符串,`replace` 文档应该链接到它,并且应该给出一个例子。我提交了一个问题:https://github.com/JuliaLang/julia/issues/26497。 (3认同)

ste*_*tej 7

自从上次回答以来它已经改变了。目前正确的版本是这个

replace("first second", r"(\w+) (?<agroup>\w+)" => s"\g<agroup> \1")
replace("a", r"." => s"\g<0>1")
Run Code Online (Sandbox Code Playgroud)

有关更多详细信息,请参阅https://docs.julialang.org/en/v1/manual/strings/ 。