有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java8正则表达式匹配非常慢

我有一个regex ^[a-z]+([a-z0-9-]+)*[a-z0-9]+$用于验证

String src = "alfjaldfjaldmflajdflakclaldkfjaldjlad,fl.adc.aldjfal";
src.matches("^[a-z]+([a-z0-9-]+)*[a-z0-9]+$");

但是,火柴没有回应。 你知道快速正则表达式吗


共 (2) 个答案

  1. # 1 楼答案

    你的问题在这里:([a-z0-9-]+)*

    您正在尝试匹配一次或多次x0或多次。这没有道理

    试试看([a-z0-9-]+)([a-z0-9-]*)哪一个适合你的需求

    此外,您还可以使用以下方法编译模式:

    Pattern compiled = Pattern.compile(regex);
    

    这可能会有所帮助,但不是你的问题

  2. # 2 楼答案

    只是在详细说明@OldCurmudgeon提供的答案

    Pattern pattern = Pattern.compile("^[a-z][a-z0-9-]*[a-z0-9]$");
    String src = "alfjaldfjaldmflajdflakclaldkfjaldjlad,fl.adc.aldjfal";
    long start = System.nanoTime();
    src.matches("^[a-z]+([a-z0-9-]+)*[a-z0-9]+$");
    long end1 = System.nanoTime();
    src.matches("^[a-z]+[a-z0-9-]*[a-z0-9]+$");
    long end2 = System.nanoTime();
    src.matches("^[a-z][a-z0-9-]*[a-z0-9]$");
    long end3 = System.nanoTime();
    pattern.matcher(src).matches();
    long end4 = System.nanoTime();
    System.out.println((end1 - start)/1000);
    System.out.println((end2 - end1)/1000);
    System.out.println((end3 - end2)/1000);
    System.out.println((end4 - end3)/1000);
    

    以微秒为单位的输出

    14377
    1130
    190
    112
    

    下面的非正则表达式方法只需10微秒

    private static boolean matches(String str)
    {
        if (str.length() < 2)
        {
            return false;
        }
        char first = str.charAt(0);
        if (!(first >= 'a' && first <= 'z'))
        {
            return false;
        }
        char last = str.charAt(str.length() - 1);
        if (!(last >= 'a' && last <= 'z') && !(last >= '0' && last <= '9'))
        {
            return false;
        }
        for (int i = 0; i < str.length() - 2; i++)
        {
            char ch = str.charAt(i + 1);
            if (!(ch >= 'a' && ch <= 'z') && !(ch >= '0' && ch <= '9') && ch != '-')
            {
                return false;
            }
        }
        return true;
    }