Java模式新线问题

时间:2011-04-11 07:52:38

标签: java regex

在阅读Pattern的文档时,它将\s声明为空格字符:[ \t\n\x0B\f\r]。那么为什么下面的第二个扫描程序返回null,如何让模式与新行字符一起使用?

import java.util.*;

public class Main
{
    public static void main(String[] args)
    {

        String pattern = "\\s*a";

        Scanner scanner1 = new Scanner("    \t a");
        Scanner scanner2 = new Scanner("  \t\n a");

        System.out.println(scanner1.findInLine(pattern));
        System.out.println(scanner2.findInLine(pattern));
    }
}

输出:

         a
null

1 个答案:

答案 0 :(得分:7)

findInLine在遇到换行符时停止(顾名思义):

"  \t\n a"
 ^^^^
   |  
   +-- this is where findInLine(...) searches for the pattern: `\s*a`

您应该使用findWithinHorizon(...)代替:

String pattern = "\\s*a";
Scanner scanner1 = new Scanner("    \t a");
Scanner scanner2 = new Scanner("  \t\n a");
System.out.printf(">%s<\n\n", scanner1.findInLine(pattern));
System.out.printf(">%s<", scanner2.findWithinHorizon(pattern, 0));

将打印:

>        a<

>   
 a<