我正在尝试使用replace
doc指定的函数
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'
.
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 string
在https://docs.julialang.org/en/stable/manual/strings/中搜索,你会在那里找到另一个例子.
自从上次回答以来它已经改变了。目前正确的版本是这个
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/ 。