我假设最多有一个括号分隔的子字符串。
当使用Perl(单击“Perl”然后检查全局和大小写不同的选项)Ruby,Python 的替代正则表达式引擎 R 时,您可以将以下正则表达式的零长度匹配替换为 '@' perl=true 或使用 PCRE 正则表达式引擎的语言,其中包括 PHP。除了 Ruby,需要设置区分大小写 (\i) 和通用 (\g) 标志。 Ruby 只需要大小写无关标志。
r = /(?:^.*\[ *|\G(?<!^)|[a-z]+ +)\K(?<=\[| )(?=[a-z][^\[\]]*\])/
例如,如果使用 Ruby,则会执行
str = "csharp 8 in a nutshell[studying programming csharp ebooks].pdf"
str.gsub(r,'@')
#=> "csharp 8 in a nutshell[@studying @programming @csharp @ebooks].pdf"
我相信我上面提到的所有语言都允许从命令行运行一个简短的脚本。 (我在下面提供了一个 Ruby 脚本。)
正则表达式引擎执行以下操作。
(?: : begin non-capture group
^.*\[ * : match beginning of string then 0+ characters then '['
then 0+ spaces
| : or
\G : asserts the position at the end of the previous match
or at the start of the string for the first match
(?<!^) : use a negative lookbehind to assert that the current
location is not the start of the string
| : or
[a-z]+ + : match 1+ letters then 1+ spaces
) : end non-capture group
\K : reset beginning of reported match to current location
and discard all previously-matched characters from match
to be returned
(?<= : begin positive lookbehind
\[|[ ] : match '[' or a space
) : end positive lookbehind
(?= : begin positive lookahead
[a-z][^\[\]]*\] : match a letter then 0+ characters other than '[' and ']'
then ']'
) : end positive lookahead
另一种可能性(以 Ruby 为例)是将字符串分成三段,修改中间的一段,然后重新连接:
first, mid, last = str.split /(?<=\[)|(?=\])/
#=> ["csharp 8 in a nutshell[",
# "studying programming csharp ebooks",
# "].pdf"]
first + mid.gsub(/(?<=\A| )(?! )/,'@') + last
#=> "csharp 8 in a nutshell[@studying @programming @csharp @ebooks].pdf"
split 使用的正则表达式为:“匹配前面为 '[' 的(零宽度)字符串((?<=\[) 是一个正向后视)或后面跟着@987654335 @((?=\]) 是一个正向预测。)通过匹配零宽度字符串split 不会删除任何字符。
gsub 的正则表达式读取,“匹配一个零宽度字符串,该字符串位于字符串的开头或前面有一个空格,后面跟着一个不是空格的字符((?! ) 是一个 negative lookahead)。也可以写成/(?<![^ ])(?! )/((?<![^ ]) 是一个negative lookbehind)。
一个变种:
first + mid.split.map { |s| '@' + s }.join(' ') + last
#=> "csharp 8 in a nutshell[@studying @programming @csharp @ebooks].pdf"
我创建了一个名为 'in' 的文件,其中包含以下两行:
Little [Miss Muffet sat on her] tuffet
eating her [curds and] whey
这是一个 (Ruby) 脚本示例,可以从命令行运行以执行必要的替换。
ruby -e "File.open('out', 'w') do |fout|
File.foreach('in') do |str|
first, mid, last = str.split(/(?<=\[)|(?=\])/)
fout.puts(first + mid.gsub(/(?<=\A| )(?! )/,'@') + last)
end
end"
这会生成一个名为 'out' 的文件,其中包含这两行:
Little [@Miss @Muffet @sat @on @her] tuffet
eating her [@curds @and] whey