views:

87

answers:

6

Hey guys,

This is my first stack message. Hope you can help.

I have several strings i need to break up for use later. Here are a couple of examples of what i mean....

fred-064528-NEEDED  
frederic-84728957-NEEDED  
sam-028-NEEDED

As you can see above the string lengths vary greatly so regex i believe is the only way to achieve what i want. what i need is the rest of the string after the second hyphen ('-').

i am very weak at regex so any help would be great.

Thanks in advance.

+2  A: 

If they are part of larger text:

(\w+-){2}(\w+)

If there are presented as whole lines, and you know you don't have other hyphens, you may also use:

[^-]*$

Another option, if you have each line as a string, is to use split (again, depending on whether or not you're expecting extra hyphens, you may omit the count parameter, or use LastIndexOf):

string[] tokens = line.Split("-".ToCharArray(), 3);
string s = tokens.Last();
Kobi
+2  A: 

Something like this. It will take anything (except line breaks) after the second '-' including the '-' sign.

var exp = @"^\w*-\w*-(.*)$";

var match = Regex.Match("frederic-84728957-NEE-DED", exp);

if (match.Success)
{
    var result = match.Groups[1]; //Result is NEE-DED

    Console.WriteLine(result);
}

EDIT: I answered another question which relates to this. Except, it asked for a LINQ solution and my answer was the following which I find pretty clear.

http://stackoverflow.com/questions/3448269/pimp-my-linq-a-learning-exercise-based-upon-another-sa-question/3448374#3448374

var result = String.Join("-", inputData.Split('-').Skip(2));

or

var result = inputData.Split('-').Skip(2).FirstOrDefault(); //If the last part is NEE-DED then only NEE is returned.

As mentioned in the other SO thread it is not the fastest way of doing this.

lasseespeholt
+1  A: 

This should work:

.*?-.*?-(.*)
vahokif
A: 

This should do the trick:

([^\-]+)\-([^\-]+)\-(.*?)$
Mark B
A: 

the regex pattern will be

(?<first>.*)?-(?<second>.*)?-(?<third>.*)?(\s|$)

then you can get the named group "second" to get the test after 2nd hyphen

alternatively

you can do a string.split('-') and get the 2 item from the array

ajay_whiz
+3  A: 

Just to offer an alternative without using regex:

foreach(string s in list)
{
   int x = s.LastIndexOf('-')
   string sub = s.SubString(x + 1)
}

Add validation to taste.

Matt Jacobsen
you'll want `s.SubString(x + 1)` here, or it includes the last `-`.
Kobi
thanks for the suggestion kobi
Matt Jacobsen