Reputation: 609
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.
Upvotes: 0
Views: 223
Reputation: 5958
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]);
}
Upvotes: 0
Reputation: 40145
//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();
Upvotes: 0
Reputation: 1500665
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);
}
Upvotes: 7