$s2 如何使用??
Topic source如果你想在替换过程中使用第二个捕获组(即 `$2`),并且想要将其用不同的标签包裹,你只需在替换字符串中指定相应的标签即可。例如,如果你想将第二个捕获组用 `<i>` 标签包裹,你可以这样修改代码:
```java
public class Main {
public static void main(String[] args) {
String s = "the quick brown fox jumps over the lazy dog.";
String r = s.replaceAll("\\s([a-z]{4})\\s([a-z]{4})\\s", " <b>$1</b> <i>$2</i> ");
System.out.println(r);
}
}
```
这样输出的结果会是:
```
the <b>quick</b> <i>brown</i> fox jumps over the lazy dog.
```
在这个例子中,第二个捕获组 `$2` 的内容被 `<i>` 和 `</i>` 包裹起来了。
public class Test01 {
public static void main(String[] args) {
String s = "the quick brown fox jumps over the lazy dog.";
String r = s.replaceAll("\\s([a-z]{4})\\s(t)", " <b>$2</b> <i>$1</i> ");
System.out.println(r);
}
}
the quick brown fox jumps <b>t</b> <i>over</i> he lazy dog.
慢慢理解吧
- 1
求女票上微博
如果我们要把搜索到的指定字符串按规则替换,比如前后各加一个
<b>xxxx</b>
,这个时候,使用replaceAll()
的时候,我们传入的第二个参数可以使用$1
、$2
来反向引用匹配到的子串。