在Java中提取正则表达式内部值
鉴于这一案文:在Java中提取正则表达式内部值,java,regex,Java,Regex,鉴于这一案文: $F{abc} and $F{def} 我需要去 abc and def 为此,我将使用这个正则表达式来查找值\$F\{\w*\},但我需要得到w*所表示的值: str.replaceAll("\\$F\{\\w*\\}", "??" ); 这是否可以通过Java函数实现,或者我需要编写例程?您可以在组中捕获文本: str=str.replaceAll(\\$F\\{(\\w*)}),“$1”); 一种方法是使用regex(\\$F\
$F{abc} and $F{def}
我需要去
abc and def
为此,我将使用这个正则表达式来查找值\$F\{\w*\}
,但我需要得到w*
所表示的值:
str.replaceAll("\\$F\{\\w*\\}", "??" );
这是否可以通过Java函数实现,或者我需要编写例程?您可以在组中捕获文本:
str=str.replaceAll(\\$F\\{(\\w*)}),“$1”);
一种方法是使用regex(\\$F\\{)\\(\\\})
您可以使用replaceAll()
删除“$F{”
和“}”
部分:
关于正则表达式:
:1.组(\\$F\\{)
“$F{”
:或|
:2.组(\\})
“}”
$1
代表对应于abc
和def
的捕获组(\\w*)
String str = "$F{abc} and $F{def}";
str = str.replaceAll("\\$F\\{(\\w*)\\}", "$1" );
System.out.println(str);
public class Main {
public static void main(String[] args) {
String str = "$F{abc} and $F{def}";
System.out.println(str.replaceAll("\\$F\\{(\\w*)\\}", "$1"));
}
}
输出:
abc and def
更新
我没有把你的问题看完。谢谢你指出这一点。下面给出了预期输出的代码,abc和def
String str = "$F{abc} and $F{def}";
str = str.replaceAll("\\$F\\{(\\w*)\\}", "$1" );
System.out.println(str);
public class Main {
public static void main(String[] args) {
String str = "$F{abc} and $F{def}";
System.out.println(str.replaceAll("\\$F\\{(\\w*)\\}", "$1"));
}
}
输出:
abc and def
$F{??} and $F{??}
您只需将给定字符串替换为捕获组(1)。原始答案中的解释对此更新仍然有效
原始答复:
您可以使用正则表达式,(\$F\{)(\w*)(\})
,将捕获组(2)替换为?
,并保留捕获组(1)和捕获组(3),如下所示:
public class Main {
public static void main(String[] args) {
String str = "$F{abc} and $F{def}";
System.out.println(str.replaceAll("(\\$F\\{)(\\w*)(\\})", "$1??$3"));
}
}
输出:
abc and def
$F{??} and $F{??}
检查正则表达式中所有组的图示,
(\$F\{)(\w*)(\})
为什么不只有一个组?