简体   繁体   中英

how to write this regex in c#

I have a string like this:

N:string of unknown length\r\n

I want "string of unknown length" read into a variable. N: is always the start of the string, and \\r\\n is always the end of the string, and i need all in between.

My c#

String pattern ="help needed"
string result = Regex.IsMatch(pattern,myString).ToString();

EDIT!! Sorry but I have found that I was very unclear about what I wanted.

The string I am looking for N:string of unknown length\\r\\n is a substring of a larger string. Fx Bla bla\\r\\n bla bla N:string of unknown length\\r\\n more bla bla N:string of unknown length\\r\\n And it will occur only once.

If it always starts with "N:" and always ends with "\\r\\n" then you don't need regular expressions at all - you can just use Substring:

string result = text.Substring(2, text.Length - 4);

(That's assuming that by "\\r\\n" you actually mean the two individual characters '\\r' and '\\n'. If you mean four characters, change the 4 to 6.)

If you want to do validation as well, I'd use:

if (text.StartsWith("N:") && text.EndsWith("\r\n"))
{
    string result = text.Substring(2, text.Length - 4);
}

Even though it is possible to write this without Regular Expression, I'm posting this in case if you want to know how to write this using regular expression.

You can use following pattern:

 N:(.*)\\\\r\\\\n 
string pattern = "N:(.*)\\r\\n";
string text = "N:Hello String World \r\n";
Regex r = new Regex(pattern, RegexOptions.IgnoreCase);
Match m = r.Match();
if(m.Success){
    Console.WriteLine("Extracted text:"+ m.Groups[0]);
}
//Regex.IsMatch(pattern,myString)//IsMatch is test, pattern <-> myString , Reverse the order
string pattern ="N:(.+)$";//. is not newline
string result = Regex.Match(myString, pattern).Groups[1].ToString();

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