user1051723
user1051723

Reputation: 25

Find a String but return the previous String

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

Answers (5)

Myrtle
Myrtle

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

Ilion
Ilion

Reputation: 6882

Assuming that is an example of a complete line:

Regex expression = new Regex("(.*) router0000");

Upvotes: -1

ken2k
ken2k

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

stema
stema

Reputation: 93026

You have two possibilities

  1. 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

  2. Match your pattern and ensure the following string with a lookahead

    \S+(?=\s+router0000)
    

    this will match only the part you want.

Upvotes: 4

Sjoerd
Sjoerd

Reputation: 75649

I can think of two ways

  • Use groups (routerbl) (router0000), and use the first group
  • Positive lookahead: routerbl (?=router000)

Upvotes: 0

Related Questions