正则表达声明

时间:2012-06-12 17:18:03

标签: java regex text-files java.util.scanner

我从来没有对正则表达式好,我似乎无法得到这个......

我试图匹配这些行的语句(这些是我正在阅读的文本文件中的两行)

Lname Fname 12.35 1
Jones Bananaman 7.1 3

目前我正在使用这个语句

reader.hasNext("\\w+ \\w+ \\d*\\.\\d{1,2} [0-5]")

但它没有输入while语句。 当我删除while时,程序读取文本文件就好了。 代码段是:

private void initializeFileData(){
    try {
        Scanner reader = new Scanner(openedPath);

        while(reader.hasNext("\\w+ \\w+ \\d*\\.\\d{1,2} [0-5]")){
            employeeInfo.add(new EmployeeFile(reader.next(), reader.next(), reader.nextDouble(), reader.nextInt(), new employeeRemove()));
        }
        for(EmployeeFile element: employeeInfo){
            output.add(element);
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}

4 个答案:

答案 0 :(得分:6)

\s字符类用于单词之间的空格:

while(reader.hasNext("\\w+\\s\\w+\\s\\d*\\.\\d{1,2}\\s[0-5]"))

<强>更新

根据Scanner类的javadoc,默认情况下它使用空格分割它的标记。您可以使用useDelimiter(String pattern)的{​​{1}}方法更改其使用的分隔符。

Scanner

http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html

答案 1 :(得分:2)

从我所看到的(如果我错了,请纠正我,因为正则表达式似乎总是欺骗我的大脑:p),你没有正确处理空间。你需要使用\ s,而不仅仅是标准的''字符

编辑:对不起,\ s。别人打败了我:p

答案 2 :(得分:0)

实际上

\w+

将为[Lname, Fname, 12, 35, 1]抓住Lname Fname 12.35 1。因此,您只需存储reader.nextLine(),然后从那里提取所有正则表达式匹配。从那里,你可以抽象一点,例如:

class EmployeeFile {

 .....

     public EmployeeFile(String firstName, String lastName,
                         Double firstDouble, int firstInt,
                         EmployeeRemove er){
          .....
     }

     public EmployeeFile(String line) {
        //TODO : extract all the required info from the string array
        //       instead of doing it while reading at the same time. 
        //       Keep input parsing separate from input reading.
        //       Turn this into a string array using the regex pattern 
        //       mentioned above

     }



}

答案 3 :(得分:0)

我创建了自己的版本,没有文件和最后一个循环,就是这样:

private static void initializeFileData() {
        String[] testStrings = {"Lname Fname 12.35 1", "Jones Bananaman 7.1 3"};
        Pattern myPattern = Pattern.compile("(\\w+)\\s+(\\w+)\\s+(\\d*\\.\\d{1,2})\\s+([0-5])");
        for (String s : testStrings) {
            Matcher myMatcher = myPattern.matcher(s);
            if (myMatcher.groupCount() == 4) {
                String lastName = myMatcher.group(1);
                String firstName = myMatcher.group(2);
                double firstValue = Double.parseDouble(myMatcher.group(3) );
                int secondValue = Integer.parseInt(myMatcher.group(4));                
                //employeeInfo.add(new EmployeeFile(lastName, firstName, firstValue, secondValue, new employeeRemove()));
            }
        }
    }

请注意,我删除了点之前的斜杠(您想要一个点,而不是任何字符)并插入括号,以便创建组。

我希望它有所帮助。

相关问题