SoFunction
Updated on 2025-03-07

Problems with regular expressions and carriage return line breaks in C#

In C#, when reading the content of the text file, there are often many carriage return line breaks ("\r\n") inside. Although they are generally invisible, they actually exist. At this time, when using regular representations for matching, it needs to be considered. I encountered this problem today:

The text file content is as follows:

DT 20180101000000
WT -1.1
SL  31.4
WL 203
DT 20180101000000
AT -4.1
BP 1023.7
HU 26
RN     99999.9
WS 1.9 92 2.0 94 3.4 79 2111 4.6 83 2103

Use regular expressions: WT\s+(?<WT>.+)$, the result is that the matching value cannot be obtained. The reason is that the text content read has many carriage return line breaks " \r\n ". For example, in WT -1.1, the actual content is

WT -1.1\r\n ”, at this time the line ending character "$" does not work. It should be said that it is to read the file content directly and use regular expressions to match it, and it does not work.

Change the regular expression to:

WT\s+(?<WT>.+)\r\n

Summarize

The above is the regular expression and carriage return line breaks in C# introduced to you by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support for my website!