在C#中的某个特定字符后获取值

问题描述 投票:1回答:8

因此,我想从value中提取stringvalue将在我的特定角色之后放置在右边,在这种情况下,我的特定角色是-并将放置在右侧。

string将如下所示:

TEST-QWE-1
TEST/QWE-22
TEST@QWE-3
TEST-QWE-ASD-4

从那个string我想提取

1
22
3
4

我是怎么用C#做的?提前致谢

c# regex string
8个回答
4
投票
mystring.Substring(mystring.IndexOf("-") + 1)

或者使用LastIndexOf,以防在最后一部分之前有其他破折号:

mystring.Substring(mystring.LastIndexOf("-") + 1)

Substringhttps://docs.microsoft.com/en-us/dotnet/api/system.string.substring?view=netframework-4.7.2

LastIndexOfhttps://docs.microsoft.com/en-us/dotnet/api/system.string.lastindexof?view=netframework-4.7.2


3
投票

我建议你学习字符串处理的Regex。在你的情况下,像[0-9]+$这样的简单正则表达式模式会匹配你的数字。

既然你说这个数字总是在你的字符串的右边,你也可以使用string.Split('-').Last()


1
投票

使用LastIndexOf获取最后一次' - '

var p = str.LastIndexOf('-');
return p >= 0 && (p + 1 < str.Length) ? str.Substring(p + 1) : "";

1
投票

您可以使用string.LastIndexOf()和string.Substring()来执行此操作。在输入中没有出现特殊字符时要小心。

string[] inputs = new string[]{ 
    "TEST-QWE-1", 
    "TEST/QWE-22",
    "TEST@QWE-3", 
    "TEST-QWE-ASD-4", 
    "TEST-QWE-ASD-4", 
    "TEST",
    "TEST-"
};
foreach(string input in inputs){
    int lastIdx = input.LastIndexOf("-");
    string output = lastIdx > -1 ? input.Substring(lastIdx + 1) : "";
    Console.WriteLine(input + " => " + output);
}
/* console outputs:
TEST-QWE-1 => 1
TEST/QWE-22 => 22
TEST@QWE-3 => 3
TEST-QWE-ASD-4 => 4
TEST-QWE-ASD-4 => 4
TEST =>
TEST- =>
*/

1
投票

我将发布另一个正则表达式来捕捉你想要的东西:-([^-]+)$

它与已发布的不同,因为它将捕获除连字符([^-]+)和字符串结尾之间的连字符(使用-)之外的所有内容($表示字符串的结尾)。

期望的结果将存储在第一个破裂组中。

代码段:

var s = "TEST-QWE-1";
var match = Regex.Match(s, "-([^-]+)$");
if (match.Success)
  Console.WriteLine(match.Groups[1]);

Demo


0
投票

你可以使用Regex,这是你需要的字符串。 [^-]+$

只需循环遍历每个字符串即可。

var regex = new Regex(@"([^-]+$)");

regex.Matches(str);

0
投票

要走的路是使用LastIndexOf方法,如下所示:

string input = "TEST-QWE-1";
var lastIndex = input.LastIndexOf("-");
var id = input.Substring(lastIndex + 1); // this is so you don't get the minus as well if you don't want it.

所以,首先我们得到我们关心的角色的最后一个索引。第二,我们使用此索引执行子字符串以获得我们想要的结果


0
投票

您可以使用像(-\d+$)这样的简单正则表达式

你也可以使用Split()并获得最后一个元素

"TEST-QWE-ASD-4".Split('-').Last();
© www.soinside.com 2019 - 2024. All rights reserved.