问题
I have string values like those below:
string str1 = "123-456-test";
string str1 = "123 - 456 - test-test";
string str1 = "123-REQ456-test";
string str1 = "123 - REQ456 - test-test";
I need to grab the entire content from string right after the 2nd dash.
I tried String.Split('-'), but it did not work. I think I need to use a regex, but I am not able to find a correct one. Please suggest.
回答1:
(?:[^-\n]+-){2}(.*)$
You can try this.Grab the capture.See demo.
https://regex101.com/r/tS1hW2/21
回答2:
This even easy with string methods like IndexOf and Substring.
string str1 = "123-456-test";
int secondIndex = str1.IndexOf('-', str1.IndexOf('-') + 1);
str1 = str1.Substring(secondIndex + 1); // test
回答3:
You can use LINQ Skip(2) with Split, no need to use a regex in C# for this task:
string input = "123-456-test";
string res = input.Contains("-") && input.Split('-').GetLength(0) > 2 ? string.Join("-", input.Split('-').Skip(2).ToList()) : input;
Result:

In case you want to use a regex by all means, you can leverage a variable-width look-behind in C#:
(?<=(?:-[^-]*){2}).+$
See regex demo
Sample code:
var rgx = new Regex(@"(?<=(?:-[^-]*){2}).+$");
Console.WriteLine(rgx.Match("123-456-test").Value);
Console.WriteLine(rgx.Match("123 - 456 - test-test").Value);
Console.WriteLine(rgx.Match("123-REQ456-test").Value);
Console.WriteLine(rgx.Match("123 - REQ456 - test-test").Value);
Output:
test
test-test
test
test-test
来源:https://stackoverflow.com/questions/30500975/need-to-get-everything-after-2nd-dash-in-string