如何在 C# 中编写仅用于数字的正则表达式?
csharpserver side programmingprogramming更新于 2025/6/26 8:22:17
正则表达式是一种可以与输入文本匹配的模式。
.Net 框架提供了一个允许此类匹配的正则表达式引擎。
模式由一个或多个字符文字、运算符或构造函数组成。
以下是正则表达式使用的基本模式元字符 −
* = 零个或多个 ? = 零个或一个 ^ = 非 [] = 范围
^ 符号用于指定非条件。
如果我们要给出范围值,例如 0 - 9 或 a-z 或 A-Z,则使用 [] 括号
示例
class Program{
public static void Main(){
string num = "123dh";
Regex regex = new Regex(@"^-?[0-9][0-9,\.]+$");
var res = regex.IsMatch(num);
System.Console.WriteLine(res);
}
}
输出
False
示例
class Program{
public static void Main(){
string num = "123";
Regex regex = new Regex(@"^-?[0-9][0-9,\.]+$");
var res = regex.IsMatch(num);
System.Console.WriteLine(res);
}
}
输出
True
示例
class Program{
public static void Main(){
string num = "123.67";
Regex regex = new Regex(@"^-?[0-9][0-9,\.]+$");
var res = regex.IsMatch(num);
System.Console.WriteLine(res);
}
}
输出
True

