Search code examples
javascriptregexregex-lookarounds

Match line breaks in lines that are not starting with a special character


I want to match all \n or \r except the ones when the line starts with a @ I have this regular expression : (?!^@.*\r*\n*)(\r*\n*) For example:

@text text text 

@text text text
The line break after this text should be matched 
The line break after this text also should be selected 

@this line break should not be selected

So the only line breaks that should be selected are the ones in the 2nd, 4th, 5th,and 6th and 7th. Any ideas?


Solution

  • Like this?

    https://regex101.com/r/bYIpiQ/2

    https://regexr.com/4s98n

    Note I do not SELECT the text, I REPLACE the \n\r or\n or \r

    const text = document.getElementById("x").innerText;
    document.getElementById("x").innerText=text.replace(/(^[^@].*)(\r\n|\r|\n)/gm,"$1<BR/>")
    #x { font-family: "Courier New", monospace;
      white-space: pre; }
    <div id="x">@line 1: text text text 
    line 2:
    @line3: text text text
    line 4: The line break after this text should be matched 
    line 5: The line break after this text also should be selected 
    line 6:
    @line 7: this line break should not be selected
    </div>