如何在文件

时间:2016-04-20 14:12:43

标签: java regex

您好我正在尝试读取文件的某些凭据,但我只想读取分号后的数据。所以我想要逐行阅读并使用REGEX,但不太确定如何做到这一点。

文件格式如下。

 Name: Johnny 
 Age : 23
 City: London 

代码:

public void readFileForDataBaseCredentials() {
        Scanner newFile = null;
        try {
            newFile = new Scanner(new FileReader(selectedFile));
        } catch (Exception e) {
            System.out.println("could not find the file");
        }

        while (newFile.hasNext()) {

        }

    }

3 个答案:

答案 0 :(得分:2)

正则表达式太过分了。只需获取:字符后的子字符串:

while (newFile.hasNext()) {
  String s = newFile.next();
  int ind = s.indexOf(":");
  if(ind != -1){
    String value = s.substring(ind); //value is what you want
  }
}

答案 1 :(得分:0)

这将有效

(?<=:)\s*([\w ]+)

<强> Regex Demo

您也可以使用

.*?:\s*([\w ]+)

[^:]+:\s*([\w ]+)

或者只是在:的基础上进行分割并获取第二个元素

Java代码

Scanner x = new Scanner(System.in);
String pattern = "(?<=:)\\s*([\\w ]+)";

Pattern r = Pattern.compile(pattern);
while (true) {
     String line = x.nextLine();
     Matcher m = r.matcher(line);
     if (m.find()) {
        System.out.println(m.group(1));
     }
}

<强> Ideone Demo

答案 2 :(得分:0)

如果您自己编写代码,那将是可取的。

让你开始:

您可以结合使用JAVA的indexOf和substring方法来实现相同的

1)逐行读取文件 2)使用:方法获取indexOf(":")索引 3)使用substring(startindex)方法获取子字符串,并将startindex作为第2步返回的索引。这个返回的子字符串是你需要的