[英]Pattern matching with string containing dots
Pattern is: 模式是:
private static Pattern r = Pattern.compile("(.*\\..*\\..*)\\..*");
String is: 字符串是:
sentVersion = "1.1.38.24.7";
I do: 我做:
Matcher m = r.matcher(sentVersion);
if (m.find()) {
guessedClientVersion = m.group(1);
}
I expect 1.1.38 but the pattern match fails. 我期待1.1.38,但模式匹配失败。 If I change to
Pattern.compile("(.*\\\\..*\\\\..*)\\\\.*");
如果我改为
Pattern.compile("(.*\\\\..*\\\\..*)\\\\.*");
// notice I remove the "."
//注意我删除了“。” before the last *
在最后一个*之前
then 1.1.38.XXX
fails 然后
1.1.38.XXX
失败
My goal is to find (xxx) in any incoming string. 我的目标是在任何传入的字符串中找到(xxx)。
Where am I wrong? 我哪里错了?
Problem is probably due to greedy-ness of your regex. 问题可能是由于你的正则表达式的贪婪。 Try this negation based regex pattern:
尝试这种基于否定的正则表达式模式:
private static Pattern r = Pattern.compile("([^.]*\\.[^.]*\\.[^.]*)\\..*");
Make your .*
matches reluctant with ?
让你的
.*
比赛不情愿 ?
Pattern r = Pattern.compile("(.*?\\..*?\\..*?)\\..*");
otherwise .*
matches the whole String
value. 否则
.*
匹配整个String
值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.