Regex match empty lines

后端 未结 2 1474
野趣味
野趣味 2020-12-22 09:37

Currently I have a regex that will take a given set of newlines and condense them. A challenge I need to solve for is to modify this regex (\\n{2,}) so that it

相关标签:
2条回答
  • 2020-12-22 09:57

    Brief

    This answer ensures whitespace at the start of a line is kept (if it contains something other than a whitespace character).


    Code

    See regex in use here

    (?:\h*\n){2,}
    

    Note: Some regex engines don't allow \h, so this will have to be replaced with [\t\p{Zs}], and if Unicode character classes are not supported, a simple list of each character such as [\t ] or [^\S\n].

    Other methods:

    (?:\n(?:[^\S\n]*(?=\n))?){2,}
    (?:\n(?:\s*(?=\n))?){2,}
    \h*\n(?:\h*\n)+
    

    Results

    Input

    **Language**
    
     - Added four languages: Italian, Portuguese (Brazil), Spanish (Mexico) and Chinese (Traditional)
    
    
    
    
    
    **Bug fixes**
    
    
     - Fixed camera jittering for passenger sitting on the back of a motorcycle with sidecar
     - Fixed camera jittering for passenger sitting on the back of a motorcycle with sidecar
    

    Output

    **Language**
    
     - Added four languages: Italian, Portuguese (Brazil), Spanish (Mexico) and Chinese (Traditional)
    
    **Bug fixes**
    
     - Fixed camera jittering for passenger sitting on the back of a motorcycle with sidecar
     - Fixed camera jittering for passenger sitting on the back of a motorcycle with sidecar
    

    Explanation

    • (?:\h*\n){2,} Match any number of horizontal whitespace character followed by a line-feed, two or more times

    Other methods

    Just to explain at least one of the other methods (and keep my original answer)

    • (?:\n(?:[^\S\n]*(?=\n))?){2,} Matches the following two or more times
      • \n Match a line-feed character
      • (?:[^\S\n]*(?=\n))? Match the following zero or one time
        • [^\S\n]* Match any whitespace character except \n any number of times
        • (?=\n) Positive lookahead ensuring what follows is a line-feed \n
    0 讨论(0)
  • 2020-12-22 10:09

    This method is shorter than the top answer:

    (\h*\n){2,}
    

    Regex101

    0 讨论(0)
提交回复
热议问题