[英]regex extract string between two characters
我想使用Java中的regex提取给定字符串中以下字符之间的字符串:
/*
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);
}
我正在使用上面给定的代码片段,它无法提取我想要的字符串。 我做错了吗? 同时,我对regex还是很陌生。
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);
}
演示: http : //ideone.com/8t2EC
如果您的输入看起来总是这样,并且始终希望输入相同的部分,则可以将其放在单个正则表达式中(具有多个捕获组):
"([^"]+)" <sip:([^@]+)@([^>]+)>
这样您就可以使用
Pattern p = Pattern.compile("\"([^\"]+)\" <sip:([^@]+)@([^>]+)>");
Matcher m = p.matcher(remoteUri);
if (m.find()) {
String s1 = m.group(1);
String s2 = m.group(2);
String s3 = m.group(3);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.