Replace all occurrences and regex

I am trying to replace two consecutive line breaks with an HTML tag <p/>. Therefore, in a line, for example:

\r\n\r\n\r\n

There are two consecutive appearances \r\n\r\n,

The result should be:

<p/><p/>

but with C # String.Replaceit only detects the first occurrence, and I just go back:

<p/>\r\n

So, I wonder if any regular expression gurus know how to detect this using regular expression?

Edit:

I decided the question is a bit confusing. Let me rephrase that. The requirement should be to replace any "\r\n"tag <p/>only if there is another "\ r \ n" in front of it.

Such lines with a line:

\r\n\r\n\r\n
  • The first \r\none has no other \r\nbefore it, nothing has to be done,
  • \r\n, \r\n, ,
  • \r\n, \r\n, .

, :

<p/><p/>
+3
4

, :

string tidyString = Regex.Replace(originalString, @"(?<=\r\n)\r\n", "<p/>");

, , , , . (, 99% .)

var sb = new StringBuilder(originalString.Length);
int startIndex = 0, nextIndex;
while ((nextIndex = originalString.IndexOf("\r\n", startIndex)) >= 0)
{
    if ((nextIndex == startIndex) && (startIndex > 0))
        sb.Append("<p/>");
    else
        sb.Append(originalString, startIndex, nextIndex - startIndex + 2);

    startIndex = nextIndex + 2;
}
sb.Append(originalString, startIndex, originalString.Length - startIndex);

string tidyString = sb.ToString();
+5

:

, "\ r\n" "\ r\n", "p".

:

, N "\ r\n" N > 1, N - 1 "p".

?

, :

|  |  |  |  |

: " , ", ? , N - 1 , N ( : N > 1).

; , , , . "\ r\n" .


"\r\n\r\n" "<p/>", "\r\n" "<p/>", . ( "\r\n\r\n"; "\r\n".)

, , , : "\r\n" "\r\n" "<p/>" ( , , ).

, . , , , ; , , .

: , string.Split "\r\n" .

, , , . .

+1

: ( )

. , .

var input = "Line1\r\nLine2\r\n\r\n\r\n<line5>";
var result = Regex.Replace(input, "(\\r\\n){2}", "<p/>");
result = Regex.Replace(result, "<p/>\\r\\n", "</p></p>");

//result equals: "Line1\r\nLine2</p></p><line5>"
+1

"\r\n\r\n\r\n"not really "two consecutive appearances "\r\n\r\n"." Yes, characters 1-4 and characters 3-6 are strings "\r\n\r\n", but they intersect each other. String.Replacecan't take that into account. It simply scans the string until it finds something to replace, replaces it, and then continues to scan the string from that point. It does not check the entire string and does not determine the various substrings to be replaced, and then replaces each of them with the specified string.

0
source

Source: https://habr.com/ru/post/1792368/


All Articles