正则表达式,试图匹配不超过一个时期?

时间:2014-07-30 12:55:05

标签: java regex

使用: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

但它根本没有告诉我什么。我在这做错了什么? :(

4 个答案:

答案 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)

如果您不想在字符串中允许多个点,那么您可以尝试下面的预测

(?=^[^.]*\.{0,1}[^.]*$).*

OR

(?=^[^.]+\.{0,1}[^.]+$).*

DEMO

答案 3 :(得分:0)

使用此正则表达式:

^[^.]*(?:(?:\.[^\.]*){0,1})$

花了很多时间来解决这个问题

演示:http://regex101.com/r/kP4mF3/1