你可以找到
(width|height)="\d+"
换成
$1="470"
. 这捕捉到
width
或
height
在组1中,在替换字符串中,您将此捕获的字符串引用为
$1
.
根据需要,模式可能变得更复杂。如果你想自由使用空格,你可以允许
\s*
周围
=
为了防止匹配,比如,
tablewidth="300"
,您可以在模式前面加上
\b
等。
也见
关于捕获组
这个
(...)
构造被称为“捕获组”。
给定此测试字符串:
i have 35 dogs, 16 cats and 10 elephants
然后
(\d+) (cats|dogs)
生成2个匹配结果(
see on rubular.com
)
-
结果1:
35 dogs
-
结果2:
16 cats
工具书类
在露比
在替换字符串中,Ruby使用
\
而不是
$
作为捕获组的后向引用的信号。
ruby-doc.org --
String#gsub
:如果字符串用作替换,则匹配的特殊变量(例如
$&
和
1美元
)无法在其中进行替换,因为在模式匹配开始之前就发生了字符串替换。然而,序列
\1
,
\2
,等等可以用来在匹配中插入连续的组。
因此,您要寻找的解决方案如下:
text = 'blah blah width="300" and height="299" more blah'
puts text.gsub(/(width|height)="\d+"/, '\1="470"')
这张照片(
as seen on ideone.com
):
blah blah width="470" and height="470" more blah