数字字符和 .&- 的正则表达式
我正在使用 C# 和 .NET,我有一个看起来像这样的正则表达式
"\D"
,它匹配所有非数字字符,但我不希望它匹配小数点 (.) 和负号 (-)。我怎样才能用正则表达式做到这一点?
所以我尝试了 Chris',它做了一些调整以使其工作:(
我有一个名称为“Original”的 TextBox)
private void Original_TextChanged(object sender, EventArgs e) {
Regex regex = new Regex(@"[^\d.-]", RegexOptions.IgnoreCase);
Match match = regex.Match(Original.Text);
if (match.Success) {
Original.Text = regex.Replace(Original.Text, "");
Original.SelectionStart = Original.TextLength;
}
}
此 Original.SelectionStart = Original.TextLength;
是因为无论何时替换它把选择放在开头,这对用户来说似乎有点奇怪......
I'm using C# and .NET and I have a Regex that looks like this
"\D"
That matches all non-numeric characters however I don't want that to match a decimal point (.) and a negative sign (-). How can I do that with regular expressions?
So I tried Chris' and it made a few adjustments to make it work:
(I have a TextBox with a name of "Original")
private void Original_TextChanged(object sender, EventArgs e) {
Regex regex = new Regex(@"[^\d.-]", RegexOptions.IgnoreCase);
Match match = regex.Match(Original.Text);
if (match.Success) {
Original.Text = regex.Replace(Original.Text, "");
Original.SelectionStart = Original.TextLength;
}
}
This Original.SelectionStart = Original.TextLength;
is because whenever it was replaced it put the selection to the beginning and that would seem a little weird to a user...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用否定字符类来排除数字
。
和-
。像这样匹配单个字符的表达式是[^\d\.\-]
。插入符号表示该类被否定。You can use a negated character class to exclude numbers,
.
, and-
. The expression for matching a single character like this is[^\d\.\-]
. The caret indicates that the class is negated.