Ruby 如何使用gsub简化正则表达式

Ruby 如何使用gsub简化正则表达式,ruby,regex,gsub,Ruby,Regex,Gsub,当\href命令中出现\时,我想用\来转义\ 通常我会编写一个正则表达式,比如s/(\\href\{.*?)\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\/code>,但我想我们在这里是一个好的选择 一行中可以有多个链接 问题 gsub可以简化这类问题吗?您可以使用两个gsub:一个带参数和一个块(用于href{…

\href
命令中出现
\
时,我想用
\
来转义
\

通常我会编写一个正则表达式,比如
s/(\\href\{.*?)\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\/code>,但我想
我们在这里是一个好的选择

一行中可以有多个链接

问题


gsub
可以简化这类问题吗?

您可以使用两个gsub:一个带参数和一个块(用于
href{…}
),一个带两个参数(用
\\\\
替换
):

如果您想从带有
ruby-e
的终端启动
test.txt
文件,您可以使用:

ruby -pe '$_.gsub(/href{[^}]+}/){ |href| href.gsub(%q|#|, %q|\#|) }' test.txt
# Here is some text with a \href{./file.pdf#section.1.5}{link} to section 1.5.
# Here is some text with a \href{./file.pdf#section.1.6}{link} to section 1.6.
# Here is some text with a \href{./file.pdf#section.1.7}{link} to section 1.7.


不要混合使用
ruby-pe
ARGF.read
,它只会读取文件的第一行

除非
\href{..}
s中包含的一个或多个URL的密码部分包含在引号中,如
http://username:“sdkfj#lkn#”@domainname.org/path/file.ext
,url中字符
#
的唯一可能位置是结尾,并分隔片段部分:
/path/path/file.rb?val=toto#片段部分

换句话说,如果我没有错的话,每个
href{…}
有一个最大的
#
可以转义。然后,您可以简单地执行以下操作:

text.gsub(/\\href{[^#}]*\K#/, "\\#")

字符类
[^#}]
禁止字符
}
并确保您始终处于花括号之间。

如果我使用
ruby-0777-pe'ARGF.read.gsub(/href{[^}+}/){124; href | href.gsub(%q |#|,%q | | | |#| | | | | | | | | |)| | | | | | |。我做错了什么?
ruby -pe '$_.gsub(/href{[^}]+}/){ |href| href.gsub(%q|#|, %q|\#|) }' test.txt
# Here is some text with a \href{./file.pdf#section.1.5}{link} to section 1.5.
# Here is some text with a \href{./file.pdf#section.1.6}{link} to section 1.6.
# Here is some text with a \href{./file.pdf#section.1.7}{link} to section 1.7.
ruby -e 'puts ARGF.read.gsub(/href{[^}]+}/){ |href| href.gsub(%q|#|, %q|\#|) }' test.txt
# Here is some text with a \href{./file.pdf#section.1.5}{link} to section 1.5.
# Here is some text with a \href{./file.pdf#section.1.6}{link} to section 1.6.
# Here is some text with a \href{./file.pdf#section.1.7}{link} to section 1.7.
text.gsub(/\\href{[^#}]*\K#/, "\\#")