繁体   English   中英

如何检测字符串在C#中是否包含数字或数字?

[英]How do I detect if a string contains either a number as a digit or written as letters in C#?

我希望能够检测一个字符串是否包含数字,以数字(0-9)或纯英文字母(一,二,三..)的形式书写。 字符串中的字母数字应检测为单个单词,而不是单词的一部分。

因此,例如:

"This string contains no numbers" = false;
"This string contains the number 1" = true;
"This string contains the number three" = true;
"This string contains a dogs bone" = false; //contains the word 'one' as part of the word 'bone', therefore returns false

在SO上找不到任何可以具体回答这个问题的内容; 它们主要与仅从字符串中提取整数有关,所以我想继续问一下。

是否有可以处理此类内容的库? 如果没有,我该如何处理? 是否有比将所有单词数字放入数组更快的方法?

如果仅是说您使用的是内置库,那么我不知道一个,那么如果有人知道更好,我会很乐意纠正的。

编辑:更新了OP的说明和AndyJ的建议

要使用单独的单词执行此操作,可以改用以下方法:

public bool ContainsNumber(string s)
{
    // This is the 'filter' of things you want to check for
    // The '...' is for brevity, obviously it should have the other numbers here
    var numbers = new List<string>() { "1", "2", "3", ... , "one", "two", "three" };

    // Split the provided string into words
    var words = s.Split(' ').ToList();

    // Checks if the list of words matches ANY of the provided numbers
    // Case and culture insensitive for better matching
    return words.Any(w => numbers.Any(n => n.Equals(w, StringComparison.OrdinalIgnoreCase)));
}

用法:

ContainsNumber( “这里没有数字”);
ContainsNumber(“数字三”);
ContainsNumber(“狗吃骨头”);

输出:


真正

编辑2:返回匹配的单词

public List<string> GetMatches(string s)
{
    var numbers = new List<string>() { "1", "2", "3", ... , "one", "two", "three" };
    var words = s.Split(' ').ToList();

    return words.Intersect(numbers, StringComparer.OrdinalIgnoreCase).ToList();
}

用法:

GetMatches(“这没有任何数字”);
GetMatches(“这有一个号码”);
GetMatches(“这个1有骨头”);
GetMatches(“ 1 2 3然后是更多”);

输出:

空值
“一”
“ 1”
“ 1”,“两个”,“ 3”

创建一个包含要在该字符串中查找并对其进行迭代的所有内容的数组。

如果您只关心单个数字,则为禁食解决方案。 如果您想使用所有数字进行运算,则需要做更多的工作.....

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM