public class ReplaceInFile { public static void main(String[] args) throws IOException { String fileName = "file.txt"; String search = "31415"; String replace = "число ПИ"; Charset charset = StandardCharsets.UTF_8; Path path = Paths.get(fileName); Files.write(path, new String(Files.readAllBytes(path), charset).replace(search, replace) .getBytes(charset)); } } 

In this class, I am looking for a text grammar in a file by complete coincidence. How to make it so that after a full match, the program reads the string before the character ; ?

Sample search

File:

 IP=123123; CONNECT=456456; DADADA dadada; DATA=321321; 

If I am looking for a CONNECT = then its value must be counted before the sign ; .

  • Give an example of the file, an example of the search string and the desired result - vp_arth
  • @vp_arth Led - aaa
  • And if you are looking for a CONN , the result should be ECT=456456 ? - vp_arth
  • @vp_arth No, I'm looking only for completely. Must be considered after = before; - aaa

2 answers 2

You can do this:

 String fileName = "file.txt"; String text = "CONNECT"; String delimiter = ";"; Optional<String> result = Files .lines(Paths.get(fileName)) .filter(e -> e.contains(text)) .map(e -> { int start = e.indexOf(text); int end = e.indexOf(delimiter, start + text.length()); return e.substring(start, end); }) .findFirst(); result.ifPresent(System.out::println); 

This solution allows you not to read the entire file.

  • The answer is not entirely correct, as it reads the result along with the text variable. - aaa

Solution using regular expressions. Searches for "value" between "CONNECT =" and ";" in line

 public static void main(String[] args) throws IOException { String string = "IP=123123; CONNECT=456456; DADADA dadada;"; String pattern1 = "CONNECT="; String pattern2 = ";"; Pattern p = Pattern.compile(Pattern.quote(pattern1) + "(.*?)" + Pattern.quote(pattern2)); Matcher m = p.matcher(string); while (m.find()) { System.out.println(m.group(1)); } } 
  • Well, that looked before sending the identical solution ... - vp_arth
  • Matcher m = p.matcher (new String (Files.readAllBytes (path), charset)); - line from the example - arkada38