Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# Regex – How to get substring from between "_" and "\r\n"

In example string:
string input = "8240617_8240608_8240573\r\n";
i need to get only the last part: 8240573.
In finale application there can be dots and letters. But it will always be end of the line and between "_" and "\r\n".

I tried code below but whit no result 🙁

string input = "8240617_8240608_8240573\r\n";
string pattern = @"-(.*?)\\r\\n";

Match match = Regex.Match(input, pattern);
if (match.Success)
{
    string extractedString = match.Groups[1].Value;
    Debug.WriteLine("Extracted substring: " + extractedString);
}
else
{
    Debug.WriteLine("Substring not found.");
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your regex pattern is off. Use this version (and keep the rest of the code the same):

string pattern = @"([^_]+)\r\n";

This regex says to match:

  • ([^_]+) match the last underscore separated term
  • \r\n followed by CRLF

Note that in your version you were matching a hyphen, and also it would have picked up across multiple terms. Also, a newline inside an @ string in C# is @"\n", with just a single backslash.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading