如何解决在Java中提取正则表达式内部值
给出以下文字:
$F{abc} and $F{def}
我需要得到
abc and def
为此,我将使用此正则表达式查找值\$F\{\w*\}
,但需要获取w*
表示的值:
str.replaceAll("\\$F\{\\w*\\}","??" );
这可以用Java函数完成还是需要编写例程?
解决方法
您可以捕获组中的文本:
str = str.replaceAll("\\$F\\{(\\w*)}","$1");
,
更新
我没有完全阅读您的问题。感谢The fourth bird指出这一点。下面给出的是预期输出abc and def
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
您需要做的就是用捕获组(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"));
}
}
输出:
$F{??} and $F{??}
检查this以获得正则表达式(\$F\{)(\w*)(\})
中所有capturing groups的插图。
一种方法是使用正则表达式(\\$F\\{)|(\\})
,您可以使用"$F{"
删除"}"
和replaceAll()
部分:
String str = "$F{abc} and $F{def}";
str = str.replaceAll("(\\$F\\{)|(\\})","");
关于正则表达式:
-
(\\$F\\{)
:1.组"$F{"
-
|
:或 -
(\\})
:2.组"}"
其他方法是在替换参数中使用捕获组引用。 $1
代表与(\\w*)
和abc
def
String str = "$F{abc} and $F{def}";
str = str.replaceAll("\\$F\\{(\\w*)\\}","$1" );
System.out.println(str);
输出:
abc and def
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。