如何使用c#从字符串中获取倒数第二个字符

Pra*_*tex 1 c# string

我想解析一个字符串以从字符串中获取倒数第二个字符。这是我想要解析的内容

[XX] G_RIMN_4000+_OLEPHI_700+ [InstalmentScheme 1]
Run Code Online (Sandbox Code Playgroud)

从上面的字符串我想得到倒数第二个字符,无论它是个位数还是两位数,所以例如1]我想要1或26]我想要26

我尝试了以下方法

string input = "[XR] Z_Prem_4000+_Delphi_700+ [InstalmentScheme 1]";

var words = input.Split(' ');
var reqWord = "";
if(words.Length > 1)
   reqWord = words[words.Length-1];
        Console.WriteLine (reqWord);
Run Code Online (Sandbox Code Playgroud)

我得到1] 结果,但我想要字符串中最后一个 ] 之前的任何数字

Ste*_*eve 6

不使用正则表达式你可以这样写

// Take the position of the last space
int pos = input.LastIndexOf(' ');

// Extract the number from that pos and remove the final ]
string number = input.Substring(pos).TrimEnd(']');

// Eventually convert it to an integer
Int32.TryParse(number, out int value);

Console.WriteLine(value);
Run Code Online (Sandbox Code Playgroud)

这种方法将为您提供“]”之前的“整个数字”,而不是最后一位数字。如果字符串以“...42]”结尾,则最后一位数字是 2 而不是 42。

如果您的目的只是获取最后一位数字,那么只需对字符串进行索引即可从字符串末尾获取字符减去 2

char digit = input[input.Length-2];
Run Code Online (Sandbox Code Playgroud)

当然,为了安全地实现此逻辑,您需要添加有关字符串长度的检查


Nse*_*ens 5

您可以使用正则表达式解析字符串,如下所示:

string input = "[XR] Z_Prem_4000+_Delphi_700+ [InstalmentScheme 1]";

var match = Regex.Match(input, @"(\d+)]$"); // gets the digits before ] at the end of the string
var reqWord = "";
if (match.Success)
{
    reqWord = match.Groups[1].Value;
}
Console.WriteLine(reqWord);
Run Code Online (Sandbox Code Playgroud)