正则表达式,尝试匹配不超过一个句点?

3

你使用哪个正则表达式来匹配上面的还是下面的? - aelor
1
我只是举了这两个作为我尝试的一些事情的例子。 - user3380255
你想允许使用多个下划线吗? - Avinash Raj
其他任何内容都可以,但不要超过一个句号。 - user3380255
http://regex101.com/r/iI1wM4/2 - hwnd
4个回答

2

要在整个输入中仅匹配一个或零个点,可以采用以下简单方法:

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
从技术上讲,由于您正在使用星号重复运算符,因此不需要?。http://regex101.com/r/iI1wM4/1 - hwnd
@hwnd 是的,你需要。将点标记为0或1个实例。我们也想匹配没有任何点的输入。 - Mena
@hwnd 只需运行它。它不会有问题。 - Mena
这正是我所需要的。谢谢!所以,^从行首开始查找,[^.] <- 这是什么?你能解释一下你在那里做了什么吗? - user3380255
@user3380255 不用谢。让我稍微评论一下Pattern-等我一下。 - Mena

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()方法,而不使用PatternMatcher API。

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

0

如果您不希望在字符串中允许多个点,则可以尝试下面的前瞻

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

或者

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

演示


0
使用这个正则表达式:
^[^.]*(?:(?:\.[^\.]*){0,1})$

花了很多时间才弄清楚这个问题

演示在这里:http://regex101.com/r/kP4mF3/1


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接