简体   繁体   中英

Regex between "\r\n"

I want to match \r\n1.11.1 Entrepreneurship und Unternehmer\r\n

blabla \r\n1.11.1 Entrepreneurship und Unternehmer\r\nEs 

I tried the following RegEx:

\\r\\n\d.\d\d.\d\s+\w\\r\\n

What should it look like?

Link: https://regex101.com/r/QNXniB/1

The pattern matches a single word character using \w but in the example data there are 1 or more word characters with spaces in between.

Note to escape the dot \. to match it literally.

\\r\\n\d\.\d\d\.\d\s+\w+(?:\s+\w+)*\\r\\n
                     ^^^^^^^^^^^^^^

See a .NET regex demo .

If you want to match actual newlines in the text you should not double escape the \\r\\n


Looking at the text when there are actual newlines, you might also match the whole line that starts with a digit followed by 1 or more repetitions of a dot and digits:

^\d+(?:\.\d+)+ .*

See a regex 101 demo

Note that in .NET \d can match digits in other languages as well.

As there is a disparity between the titles format {index}. (ending with a . as in 1. Entrepreneurship ) vs {index}.{subindex} (not ending with a . as in n1.11.1 Entrepreneurship und Unternehmer ) we're going to need to check for both.

Check the results here .

The regex:

/(?:(?:\\r\\n)|^)(?<index>[0-9]+\.(?:[0-9]+\.?)*)(?<title>.+?)(?:(?:\\r\\n)|$)/gm

will match all headings starting with an index in the form <index>. + 0 or more sub-indexes in the form <subindex>. or <subindex> .

You also need to handle the condition of the string start and end where we won't have a \r\n sequence. This is done through (?:(?:\\r\\n)|^) and (?:(?:\\r\\n)|$) respectively.

After you match with the given regex, you can access your index and title directly by the named groups index and title ( title should be trimmed).

string text = "<your-text>";
Regex regex = new Regex("<regex>");

var match = regex.Match(text);

if (match.Success)
{
    var index = match.Groups["index"].Value;
    var title = match.Groups["title"].Value.Trim();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM