Reputation: 25
I'm trying to find a String in a Textfile. I'm using the RegEx Method for that. But I need to get the Previous String, which is existing before the found String, as Method Output. How can i do it with c#? Can anyone give me some Idea?
For Example:
In that Textfile is a Line with 'routerbl router0000;'
I'm searching 'router0000;'
and if i find 'router0000;'
then i want to get 'routerbl'
.
Upvotes: 1
Views: 135
Reputation: 5841
Use the expression (.*)(?=\srouter0000)
to find the text before the router0000 text.
string resultString = null;
try
{
resultString = Regex.Match(part, @"(.*)(?=\srouter0000)", RegexOptions.Multiline).Value;
} catch (ArgumentException ex)
{
// Syntax error in the regular expression
}
Upvotes: 0
Reputation: 6882
Assuming that is an example of a complete line:
Regex expression = new Regex("(.*) router0000");
Upvotes: -1
Reputation: 49013
It won't answer your question about regular expressions, but if the only rule is to return the first part of your string before a specific sub-string, then you could using something more simple than regexp:
string test = "routerbl router0000;";
string matchingValue = "router000";
int matchingValueIndex = test.IndexOf(matchingValue);
string leftPart;
if (matchingValueIndex >= 0)
{
leftPart = test.Substring(0, matchingValueIndex);
}
Upvotes: 1
Reputation: 93026
You have two possibilities
Match what you want using a capturing group, something like this
(\S+)\s+router0000
and you will find your result in the capturing group 1
Match your pattern and ensure the following string with a lookahead
\S+(?=\s+router0000)
this will match only the part you want.
Upvotes: 4