0

我的问题涉及从字符串中提取整数(在 C# 中)。有一个字符串可以在最后的圆括号中包含一个整数正数(不带前导零),例如“这是一个字符串(125)”。我想编写一个代码来验证它是否具有这种形式,如果是,则从中提取数字和其余部分。例如,如果字符串是“This is a string (125)”,则结果应该是“This is a string”(类型:字符串)和 125(整数)。如果字符串是“Another example (7)”,结果应该是“Another example”,并且 7. 正则表达式有用,还是我应该编写一个解析函数?

4

4 回答 4

0

使用正则表达式\((\d})\)$,将字符串末尾的数字作为一个组。

于 2013-11-07T05:54:54.530 回答
0

你可以试试这个

string firstPart = Regex.Match(inputString, @"\(([^)]*)\)").Groups[0].Value;
int number;
Int32.TryParse(Regex.Match(inputString, @"\(([^)]*)\)").Groups[1].Value, out number);

编辑:

显然你可以优化它而不是做两次匹配,但这显示了如何使用它。

于 2013-11-07T05:52:04.287 回答
0

如果输入值始终具有相同的结构(如 /type/bracket/value/bracket),那么您可以通过以下方式实现:
1)RegEx
2)String.Split()
3)String.IndexOf()

于 2013-11-07T05:52:08.850 回答
0
        string testString = "This is a string (125)asbcd";
        string[] stringPart = testString.Split('(', ')');

这里 stringPart[0] 是字符串部分,stringPart[1] 是数字部分。

于 2013-11-07T06:15:34.730 回答