Reputation: 1901
I need to search a large string for a particular substring. The substring will start with Testing=
but everything within the double quotes could be different because its a user login.
So examples of the substring I need are
Testing="network\smithj"
or
Testing="network\rodgersm"
Do my requirements make sense? How can I do this in C#?
Upvotes: 4
Views: 8043
Reputation: 5295
If the string you're searching is very large, you might not want to use regular expressions. Regexes are relatively slow at matching and will typically examine every character. Instead, lookup the Boyer-Moore string matching algorithm, which typically examines only a fraction of the characters. The CLR implementation for string.IndexOf(string) may or may not use this algorithm - you'd have to check.
Ah, here's a useful link with some benchmark results: http://www.arstdesign.com/articles/fastsearch.html
Upvotes: 0
Reputation: 138874
This is a great application of a regular expression.
"Testing=\"[^\"]*\""
You will use it like so:
Regex reg = new Regex("Testing=\"[^\"]*\"");
string login = reg.Match(yourInputString).Groups[0].Value;
The above works with your two given test cases.
Wikipedia has a great article on Regular Expressions if you are not familiar with them. And if you search google you can find a wealth of info on how to use Regular Expressions in C#.
Upvotes: 10
Reputation: 1500495
Something like:
const string Prefix = "Testing=\"";
static string FindTestingSubstring(string text)
{
int start = text.IndexOf(Prefix);
if (start == -1)
{
return null; // Or throw an exception
}
int end = text.IndexOf('\"', start + Prefix.Length);
if (end == -1)
{
return null; // Or throw an exception
}
return text.Substring(start + Prefix.Length, end - start - Prefix.Length);
}
An alternative is to use a regular expression - but when the pattern is reasonably simple, I personally prefer simple string manipulation. It depends on how comfortable you are with regexes though :)
Upvotes: 9