Search code examples
regexregex-negationregex-lookaroundsregex-groupregex-greedy

Regex: How to match instances of text, including spaces and new lines?


I want a regular expression which will match one or more instances of text followed by a newline. Following the final match of text followed by a newline I would like for a single further newline, then no more. How would I go about achieving this?

I am having difficulty in enforcing the one new line rule.

My (wrong) attempts include: [^\n]+\n\n ([^\n]+\n[^\n]+)*\n\n

An example of text i would like to match is:

"Hello text\nMore text\nLast one\n\n"

With a non-match on both:

"Hello text\nMore text\nLast one\n\n\n"

"Hello text\nMore text\nLast one\n"

PLease help me. thanks


Solution

  • You're asking to match any number of lines of text, followed by only 1 additional newline at the end, simply: ^(.+\n)+\n(?!\n) will do what you'd like.

    Example here: https://regex101.com/r/Hy3buP/1

    Explanation:

    ^                        - Assert position at start of string
     (.+\n)+                 - Match any positive number of lines of text ending in newline
            \n               - Match the next newline
              (?!\n)         - Do a negative lookahead to ascertain there are no more newlines.