gpt4 book ai didi

c# 正则表达式只包含字符串中的数字字符

转载 作者:太空宇宙 更新时间:2023-11-03 17:09:45 26 4
gpt4 key购买 nike

我想检查一个未定义长度的字符串是否只包含数字。示例:

"234324" = true
"er32" = false
"1" = true

我尝试解决这个问题的方法是这样的:

public bool Validate(string input)
{
return (Regex.IsMatch(input, @"^\d+$")) ? true : false;
}

现在我不是正则表达式的大英雄,但根据我在互联网上可以找到的所有内容,表达式 "^\+$""^[0-9] $" 会工作,但不会 :(

最佳答案

这里不需要RegEx,可以用int.TryParse检查 string 是否为有效整数。

public bool Validate(string input)
{
int myNumber;
return int.TryParse(input, out myNumber);
}

请注意 IsMatch 已经返回一个 bool? true : false 没用。

关于c# 正则表达式只包含字符串中的数字字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8534545/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com