需要在字符串中的第二个破折号之后获取所有内容吗?
need to get everything after 2nd dash in string?
我有如下所示的字符串值:
string str1 = "123-456-test";
string str1 = "123 - 456 - test-test";
string str1 = "123-REQ456-test";
string str1 = "123 - REQ456 - test-test";
我需要在第二个破折号后立即从字符串中获取全部内容。
我试过String.Split('-')
,但没用。我想我需要使用正则表达式,但找不到正确的正则表达式。请提出建议。
(?:[^-\n]+-){2}(.*)$
您可以尝试 this.Grab capture.See 演示。
您可以将 LINQ Skip(2)
与 Split
一起使用,无需在 C# 中使用正则表达式来完成此任务:
string input = "123-456-test";
string res = input.Contains("-") && input.Split('-').GetLength(0) > 2 ? string.Join("-", input.Split('-').Skip(2).ToList()) : input;
结果:
如果你想使用正则表达式,你可以利用 variable-width look-behind in C#:
(?<=(?:-[^-]*){2}).+$
示例代码:
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);
输出:
test
test-test
test
test-test
使用 IndexOf
and Substring
这样的字符串方法甚至很容易。
string str1 = "123-456-test";
int secondIndex = str1.IndexOf('-', str1.IndexOf('-') + 1);
str1 = str1.Substring(secondIndex + 1); // test
我有如下所示的字符串值:
string str1 = "123-456-test";
string str1 = "123 - 456 - test-test";
string str1 = "123-REQ456-test";
string str1 = "123 - REQ456 - test-test";
我需要在第二个破折号后立即从字符串中获取全部内容。
我试过String.Split('-')
,但没用。我想我需要使用正则表达式,但找不到正确的正则表达式。请提出建议。
(?:[^-\n]+-){2}(.*)$
您可以尝试 this.Grab capture.See 演示。
您可以将 LINQ Skip(2)
与 Split
一起使用,无需在 C# 中使用正则表达式来完成此任务:
string input = "123-456-test";
string res = input.Contains("-") && input.Split('-').GetLength(0) > 2 ? string.Join("-", input.Split('-').Skip(2).ToList()) : input;
结果:
如果你想使用正则表达式,你可以利用 variable-width look-behind in C#:
(?<=(?:-[^-]*){2}).+$
示例代码:
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);
输出:
test
test-test
test
test-test
使用 IndexOf
and Substring
这样的字符串方法甚至很容易。
string str1 = "123-456-test";
int secondIndex = str1.IndexOf('-', str1.IndexOf('-') + 1);
str1 = str1.Substring(secondIndex + 1); // test