need to get everything after 2nd dash in string?

痞子三分冷 提交于 2021-02-16 09:10:02

问题


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:

enter image description here

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!