3

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.

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Roooss
  • 626
  • 1
  • 9
  • 24
  • I used your problem as a little learning exercise: http://stackoverflow.com/questions/3448269/pimp-my-linq-a-learning-exercise-based-upon-another-sa-question Thanks! – Matt Jacobsen Aug 10 '10 at 11:33

6 Answers6

4

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
  • 5,814
  • 4
  • 35
  • 49
2

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
  • 135,331
  • 41
  • 252
  • 292
2

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.

Pimp my LINQ: a learning exercise based upon another post

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.

Community
  • 1
  • 1
Lasse Espeholt
  • 17,622
  • 5
  • 63
  • 99
1

This should work:

.*?-.*?-(.*)
chpatrick
  • 461
  • 6
  • 14
0

This should do the trick:

([^\-]+)\-([^\-]+)\-(.*?)$
Mark Bell
  • 28,985
  • 26
  • 118
  • 145
0

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
  • 17,573
  • 4
  • 36
  • 44