4

我认为正则表达式太过分了,我也需要一些时间来编写一些代码(我想我现在应该学习一些正则表达式)。

将字符串分隔为字母数字字符串的最简单方法是什么?它总是 LLLLDDDDD。我只想要字母(l),通常只有 1 或 2 个字母。

4

4 回答 4

11

修剪结束

string result = input.TrimEnd(new char[]{'0','1','2','3','4','5','6','7','8','9'});
// I'm sure using LINQ and Range can simplify that.
// also note that a string like "abc123def456" would result in "abc123def"

但是 RegEx 也很简单:

string result = Regex.Match(input,@"^[^\d]+").Value;
于 2009-09-27T19:08:43.353 回答
10

我更喜欢 Michael Stum 的正则表达式答案,但这里也是一种 LINQ 方法:

string input = "ABCD1234";
string result = new string(input.TakeWhile(c => Char.IsLetter(c)).ToArray());
于 2009-09-27T19:23:54.383 回答
3

您可以使用与数字匹配的正则表达式来删除它们:

input = Regex.Replace(input, "\d+$", String.Empty);

老式循环也不错,它实际上应该是最快的解决方案:

int len = input.Length;
while (input[len-1] >= '0' && input[len-1] <= '9') len--;
input = input.Substring(0, len);
于 2009-09-27T19:31:41.573 回答
0

他们明白了 - 请注意,好的解决方案使用 not 运算符来使用您的问题描述:“不是数字”如果您在前面有数字,从我有限的收益看来,您必须拥有所谓的捕获组才能通过不管它在字符串的前端是什么。我现在使用的设计范例不是分隔符,后跟分隔符,然后是左大括号。

这导致需要一个不在结果集中的分隔符,一方面可以很好地建立数据分隔符的 ascii 值,例如 0x0019 / 0x0018 等等。

于 2009-09-27T19:32:23.950 回答