使用:http://www.regexplanet.com/advanced/java/index.html
并测试正则表达式:
\.{0,1}
(?=.*?\.{0,1})
我引用了这个:http://www.rexegg.com/regex-lookarounds.html,尝试了其他组合,但没有任何方法按我想要的方式工作。
例如,对于测试输入和匹配,我期待..
lo.cat.tion - no match
location - match
loc_ation - match
loc.ation - match
但它根本没有告诉我什么。我在这做错了什么? :(
答案 0 :(得分:1)
可以通过以下方式实现在整个输入中仅匹配一个点或不匹配点的一种简单方法:
String[] input = {
"lo.cat.tion", // - no match
"location", // - match
"loc_ation", // - match
"loc.ation" // - match
};
// | start of input
// || non dots, 0 or more
// || | 1 dot or nothing (dot requires \\escaping here)
// || | | non dots, 0 or more
// || | | | end of input
Pattern p = Pattern.compile("^[^.]*\\.?[^.]*$");
for (String s: input) {
Matcher m = p.matcher(s);
// we use "matches" instead of "find", to match the entire input here,
// although in this context both methods yield equivalent results
System.out.printf("Matches for \"%s\"? %b%n", s, m.matches());
}
<强>输出强>
Matches for "lo.cat.tion"? false
Matches for "location"? true
Matches for "loc_ation"? true
Matches for "loc.ation"? true
答案 1 :(得分:1)
使用String#indexOf()
方法的简单程序。只需计算字符串中的点数(小数点)即可。
public static boolean isValid(String s) {
int count = 0;
int fromIndex = -1;
while ((fromIndex = s.indexOf(".", fromIndex + 1)) != -1) {
count++;
if (count > 1) {
return false;
}
}
return true;
}
...
System.out.println(isValid("lo.cat.tion")); // false
System.out.println(isValid("location")); // true
System.out.println(isValid("loc_ation")); // true
System.out.println(isValid("loc.ation")); // true
或者在不使用String.matches()
或Pattern
API的情况下使用Matcher
方法。
String regexPattern = "[^.]*\\.?[^.]*";
System.out.println("lo.cat.tion".matches(regexPattern)); // false
System.out.println("location".matches(regexPattern)); // true
System.out.println("loc_ation".matches(regexPattern)); // true
System.out.println("loc.ation".matches(regexPattern)); // true
答案 2 :(得分:0)
答案 3 :(得分:0)