代码之家  ›  专栏  ›  技术社区  ›  Zombies

在不编译正则表达式的情况下在java中进行字符串拆分/标记化?

  •  0
  • Zombies  · 技术社区  · 13 年前

    标准Java API中是否有一个速记符号允许我从字符串中获取令牌 1^2^3^4 在1行中?我想说的是要提取的第三个元素“3”。我不想要任何能编译正则表达式的东西。将其传递到预编译的正则表达式中是可以的,但每次调用方法时都要不断编译正则表达式会损害CPU。

    4 回复  |  直到 13 年前
        1
  •  3
  •   Joachim Isaksson    13 年前

    您可以使用预编译的 Pattern ;

    static Pattern regex = Pattern.compile("\\^");
    
    private static String getEntry(String input, int which)
    {
        return regex.split(input)[which];
    }
    

    …或者,只需直接用代码执行,而不是使用regex,因为它不会创建不需要的String对象,所以应该会更快。

    private static String getEntry(String input, int which)
    {
        int left, right = -1;
        do {
            left = right;
            right = input.indexOf('^', right+1);
        }
        while(which-- > 0 && right >= 0);
    
        if(which != -1)
            return null;
    
        if(right == -1)
            return input.substring(left+1);
    
        return input.substring(left+1, right);
    }
    
        2
  •  1
  •   mthmulders    13 年前

    您可以使用在Java中编译正则表达式 Pattern.compile ,这将导致 Pattern 对象您可以随心所欲地重复使用该对象,而不必每次都编译regex。只需将编译后的模式存储在一个变量中,这样您就可以在每次需要时检索它。

    如果定义的图案与 ^ ,您可以创建 Matcher 对象,该对象将您的模式与您的输入相匹配,使用 Pattern.matcher() 这个 Matcher.group(int) 方法将允许您访问给定输入中的特定匹配。

        3
  •  1
  •   drael    13 年前

    有一个Scanner类,它可以让你定义一个拆分器字符,这样你就可以调用next()函数,直到找到你想要的元素。在这种情况下不需要使用正则表达式。

        4
  •  0
  •   Visionary Software Solutions    13 年前

    我想,如果你想完全避免使用正则表达式来解决性能问题,你可以尝试 Apache Commons StringUtils split() 其进行迭代处理。我还没有把它与 Java standard library one ,但从来源来看,我很难想象会有什么显著的性能差异。