How to delete the specific lines that starts and ends with specific string in a file in java?

后端 未结 2 630
眼角桃花
眼角桃花 2021-01-17 02:47

I have a file abc.txt that has lines as

abc.txt

Ethernet 1/1 

Ethernet 1/2

interface 3

abs_mod_
jjj
kkkk
ll
abs_mod_

interface 6

interface 7
         


        
2条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-17 03:28

    Load the entire file into memory, then use regex to remove the lines you don't want.

    Using Java 11+

    String text = Files.readString(Paths.get("abc.txt"));
    text = text.replaceAll("(?sm)^abs_mod_(?:.*?^abs_mod_)?.*?\\R", "");
    System.out.println(text);
    

    Using Java 7+

    String text = new String(Files.readAllBytes(Paths.get("abc.txt")), StandardCharsets.UTF_8);
    text = text.replaceAll("(?sm)^abs_mod_(?:.*?^abs_mod_)?.*?\\R", "");
    System.out.println(text);
    

    Output

    Ethernet 1/1 
    
    Ethernet 1/2
    
    interface 3
    
    
    interface 6
    
    interface 7
    

    Explanation

    (?              Set flags:
      s               DOTALL     '.' matches any character, including a line terminator
      m               MULTILINE  '^' and '$' match just after/before a line terminator
    )
    ^abs_mod_       Match 'abs_mod_' at beginning of line
    (?:             Start optional non-capturing group
      .*?             Match any text (including line terminators) until:
      ^abs_mod_         Match 'abs_mod_' at beginning of line
    )?              End optional section
    .*?             Match any text up to:
    \R                Match line terminator
    

    Both .* have the extra ? making them "reluctant", so they don't cross the "ending" match. The . in the second .*? won't actually match a line terminator since the ending match is a line terminator.

    The optional section is because you said: "delete the lines in between abs_mod_ and also lines starting with abs_mod_"

    The regex is really these two blended together:

    (?sm)^abs_mod_.*?^abs_mod_.*?\R   Lines between lines starting with 'abs_mod_' (inclusive)
    (?m:^)abs_mod_.*\R                Single line starting with 'abs_mod_'
    

提交回复
热议问题