alice
alice

Reputation: 33

find a pattern in a file in java

I have a file, when I find

name="john"

I want to return john. I tried doing below:

Scanner scanner = new Scanner(new File("file.txt"));
    List<String> list=new ArrayList<>();
    while(scanner.hasNextLine()){
        list.add(scanner.nextLine()); 
     }

    for(String str:list){
        Pattern pattern = Pattern.compile("name='([^']*)'");
        if(str.contains(pattern))

    }

and here I don't know how to continue, how do I return it? I have read the question here but can't make it work.

Upvotes: 2

Views: 289

Answers (2)

Karol Dowbecki
Karol Dowbecki

Reputation: 44952

Your current pattern is incorrect, it expects ' while the file is using ". You might want to improve the pattern further, but the whole problem can be accomplished with streams:

Pattern pattern = Pattern.compile("name=\"(.+)\"");
try (BufferedReader reader = Files.newBufferedReader(Paths.get("file.txt"))) {
  return reader.lines()
      .map(pattern::matcher)
      .filter(Matcher::matches)
      .map(m -> m.group(1))
      .findFirst()
      .orElseThrow(IllegalArgumentException::new);
}

Upvotes: 4

Aman Chhabra
Aman Chhabra

Reputation: 3894

What you need to do is to use group 1 that is being matched in the regex: You can do it as below:

matcher.group(1)

Working example:

List<String> list = new ArrayList<>();
list.add("name=\"john\"");
for(String str:list){
        Pattern pattern = Pattern.compile("name=\"([^']*)\"");
        Matcher matcher = pattern.matcher(str);
        if(matcher.matches())
            System.out.println(matcher.group(1)); // having the value john
    }

Jshell Output:

jshell> for(String str:list){
   ...>         Pattern pattern = Pattern.compile("name=\"([^']*)\"");
   ...>         Matcher matcher = pattern.matcher(str);
   ...>         if(matcher.matches())
   ...>             System.out.println(matcher.group(1));
   ...>     }

   john

Upvotes: 1

Related Questions