How to remove initial numeric characters from a string in C#?
如何使用正则表达式从字符串中删除第一个数字字符?字符串str=20be45;
输出>BE45
- 您也删除了第二个数字字符。
- 是的,这就是我要找的。(初始数字字符)
这是雷杰克斯
1 2
| string text ="20Be45";
string replaced = Regex.Replace(text,"^[0-9]+", string.Empty); |
但是,我编程了15年没有使用正则表达式,你知道吗?我很高兴,我的节目也很好。
1 2 3 4 5 6 7 8
| int i = 0;
while (i < text.Length && text[i] >= '0' && text[i] <= '9')
{
i++;
}
text = text.Substring(i); |
- Char.isnumber or char.isdigit?
- @Jamesbarras EDOCX1@但我很老了,所以我仍然使用的是=======================================(and has the advantage that it is perfectly readable,without need to think if it means unicode digit or 0-9 digit as with the dichotomy ISDIGIT/ISNUMBER)
- RegExp:Now you have two problems;)
- 对我来说,太老了,我有同样数目的年规划作为你…一个正常的表达方式是最好的处理方式与想法一样。
- @Zoharpeled c doesn't have a regexp included…c++did't have until some years ago.VB 6 Didn't have.他们有其他的"Branch"(perl/php/python)他们有。
- 有什么关系?The question was about C.35;and Regex.BTW,as far as I can remember,Javascaript supports regex for at least 15 years.
- @Zoharpeled that you followed a different road to programming.c/C++and VB programmers did n't use regexes,while p*programmers(and javascript)(so web programmers)did.
- 当我同意你不需要使用规则在这里,我不认为你应该重新发明的地方。3.net framework comes with a lots of functionality that is written by smart guys and is ready to be used.使用此提示。
- @Xanatos:Why does that matter?I can't even read php,but I have worked for a long time with Javascript.有什么错吗?Do you think the language someone used to write code make that some better programmer?
- @Zoharpeled I'm saying that until some years ago half of the programmers could don't use regexese,but still lived happy.他们不使用他们,因为他们的语言没有支持他们。The other half of the programmers used languages that support them(and often used them).Some of these languages supported regexes as first level objects(like Javascript).我从来没有说过任何事情。
- 好吧,所以你有一些问题反对常规的表达。I get that,a lot of programmers don't like regular expression and for good reasons.但是,对于像这样的问题,当正常表达是非常简单和可接受的,我看不出有什么好的理由去超越你所做的。如果他要求核实一个日期是否有效,那将是一个不同的故事。
这是另一个使用string.trimstart方法的解决方案:
1 2
| string text ="20Be45";
string replaced = text.TrimStart('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'); |
另一个非regex版本:
1 2
| var text ="20Be45";
var result = string.Concat(text.SkipWhile(char.IsDigit)); |