gpt4 book ai didi

java - 我可以替换 Java 正则表达式中的组吗?

转载 作者:IT老高 更新时间:2023-10-28 11:38:59 27 4
gpt4 key购买 nike

我有这段代码,我想知道是否可以只替换 Java 正则表达式中的组(不是所有模式)。代码:

 //...
Pattern p = Pattern.compile("(\\d).*(\\d)");
String input = "6 example input 4";
Matcher m = p.matcher(input);
if (m.find()) {

//Now I want replace group one ( (\\d) ) with number
//and group two (too (\\d) ) with 1, but I don't know how.

}

最佳答案

使用 $n (其中 n 是一个数字)引用 replaceFirst(...) 中捕获的子序列.我假设您想用文字字符串 "number" 替换第一组,用第一组的值替换第二组。

Pattern p = Pattern.compile("(\\d)(.*)(\\d)");
String input = "6 example input 4";
Matcher m = p.matcher(input);
if (m.find()) {
// replace first number with "number" and second number with the first
String output = m.replaceFirst("number $3$1"); // number 46
}

考虑 (\D+)对于第二组而不是 (.*) . *是一个贪婪的匹配器,首先会消耗最后一个数字。匹配器在实现最终 (\d) 时将不得不回溯。没有可匹配的,在它可以匹配到最后一个数字之前。

关于java - 我可以替换 Java 正则表达式中的组吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/988655/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com