How do I remove trailing whitespace using a regular expression?

后端 未结 10 2071
无人及你
无人及你 2021-01-30 04:00

I want to remove trailing white spaces and tabs from my code without removing empty lines.

I tried:

\\s+$

and:

([^\\n]         


        
相关标签:
10条回答
  • 2021-01-30 04:24

    Regex to find trailing and leading whitespaces:

    ^[ \t]+|[ \t]+$
    
    0 讨论(0)
  • 2021-01-30 04:24

    To remove trailing white space while ignoring empty lines I use positive look-behind:

    (?<=\S)\s+$
    

    The look-behind is the way go to exclude the non-whitespace (\S) from the match.

    0 讨论(0)
  • 2021-01-30 04:25

    Try just removing trailing spaces and tabs:

    [ \t]+$
    
    0 讨论(0)
  • 2021-01-30 04:37

    In Java:

    
    
    String str = "    hello world  ";
    
    // prints "hello world" 
    System.out.println(str.replaceAll("^(\\s+)|(\\s+)$", ""));
    
    
    
    0 讨论(0)
提交回复
热议问题