我想使用 Java 中的正则表达式提取给定字符串中以下字符之间的字符串:
/*
1) Between \" and \" ===> 12222222222
2) Between :+ and @ ===> 12222222222
3) Between @ and > ===> 192.168.140.1
*/
String remoteUriStr = "\"+12222222222\" <sip:+12222222222@192.168.140.1>";
String regex1 = "\"(.+?)\"";
String regex2 = ":+(.+?)@";
String regex3 = "@(.+?)>";
Pattern p = Pattern.compile(regex1);
Matcher matcher = p.matcher(remoteUri);
if (matcher.matches()) {
title = matcher.group(1);
}
我正在使用上面给出的代码片段,它无法提取我想要的字符串。我做错了什么吗?同时,我对正则表达式还很陌生。
最佳答案
matches()
方法尝试将正则表达式与整个字符串进行匹配。如果你想匹配字符串的一部分,你需要 find()
方法:
if (matcher.find())
但是,您可以构建一个正则表达式来同时匹配所有三个部分:
String regex = "\"(.+?)\" \\<sip:\\+(.+?)@(.+?)\\>";
Pattern p = Pattern.compile(regex);
Matcher matcher = p.matcher(remoteUriStr);
if (matcher.matches()) {
title = matcher.group(1);
part2 = matcher.group(2);
ip = matcher.group(3);
}
关于java - 正则表达式提取两个字符之间的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10724038/