使用.NET正则表达式来检索之后的第二个字符串的一部分“ - ” [英] Using .NET RegEx to retrieve part of a string after the second '-'
问题描述
这是我的第一个堆栈消息。希望能帮到你。
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.
在此先感谢。
推荐答案
这样的事情。这将需要任何东西(除换行符)后的第二个' - '包括' - '标志
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);
}
编辑:我回答涉及到这个另外一个问题。除非,它要求对LINQ的解决方案,我的答案是下面,我觉得pretty的清晰。
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.
<一个href="http://stackoverflow.com/questions/3448269/pimp-my-linq-a-learning-exercise-based-upon-another-sa-question/3448374#3448374">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));
或
var result = inputData.Split('-').Skip(2).FirstOrDefault(); //If the last part is NEE-DED then only NEE is returned.
正如其他SO线程是不是这样做的最快的方法。
As mentioned in the other SO thread it is not the fastest way of doing this.
这篇关于使用.NET正则表达式来检索之后的第二个字符串的一部分“ - ”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!