有没有什么简单的方法可以在不使用正则表达式的情况下比较字母数字

本文关键字:情况下 正则表达式 比较 数字 简单 什么 方法 有没有 | 更新日期: 2023-09-27 18:21:29

我试图比较有时前面有字符A-Z的字符串,看看它是否存在于列表中。

因此,比较像225225.这样的东西,看看它是否存在于像这样的值列表中

225.0
235.9
A23.8
B56.0
345.8

我的正则表达式在225.上失败(带有句点)。它应该与列表中的第一个匹配,因为它们是相同的数值。

if (codesList[i].IndexOf(".") < 0)
{
    code = new System.Text.RegularExpressions.Regex("''b" + codesList[i].Replace(".", "[.]") + "(?![.])''b");
}
else
{
    code = new System.Text.RegularExpressions.Regex("''b" + codesList[i].Replace(".", "[.]") + "''b");
}
if (code.IsMatch(stringToFind))
{
    found = true;
}

所以我想通过转换成十进制来使用精确的数值。但是,如果值前面有一个字符,那么这是不起作用的。

编辑->我不知道我还能澄清多少,除了我想看看字符串是否与列表中的字母数字值匹配。但它必须在数值方面匹配(暂时忽略字母字符),一旦匹配,字母字符就必须完全匹配。

因此A57.0应该与A57相匹配。和A57但A57.01与A57不匹配。或者A57,Z57也不会。

与常规数值相同234.0必须等于234和234。

有没有什么简单的方法可以在不使用正则表达式的情况下比较字母数字

首先,您应该从尝试比较的字符串中删除所有非数字字符。

然后转换为数字并进行比较。

    bool found = false;
    foreach(var code in codesList)
    {
        Regex rgx = new Regex(@"[^0-9'-'.]");
        code = rgx.Replace(code, "");
        double num;
        if(double.TryParse(code, num))
        {
            // floating point number comparison should be done against a delta,
            // adjust as needed
            if(Math.Abs(num - numberToFind) < 0.000001d)
            {
                found = true;
                break;
            }
        }    
    }

这应该会对你有所帮助,但我仍然不明白你为什么需要搜索字符串中的".":

List<string> codelist = new List<string>()
{
     "225.01",
     "225.00",
     "235.9",
     "A23.8",
     "B56.0",
     "345.8",
     "ZR5.0"
};
string stringToFind = "225.";
bool found = false;
foreach (string item in codelist)
{
     string[] parts = item.Split('.');
     //Convert.ToInt32(parts[1]),if its 01 it will be false
     //because the int returned will be 1 so only fractions
     //with only 0 will be true
     if (Convert.ToInt32(parts[1]) == 0)
     {
         //will be true for the item "225.00" or "225.0"
         if ((found = stringToFind.Contains(parts[0])) == true)
            break;
     }
}

我们做stringToFind.Contains(parts[0]))是因为这是一个"变化"的字符串,它可以有点也可以没有点,而parts[0]在这个例子中总是只有数字225。

bool Match(string s1, string s2) {
    string alphas = "ABCDEFGHIJKLMNOPQRSVWXYZ";
    foreach (char chr in alphas) {
        s1 = s1.Replace(chr.ToString(), "");
        s2 = s2.Replace(chr.ToString(), "");
    }
    decimal d1 = decimal.Parse(s1);
    decimal d2 = decimal.Parse(s2);
    return d1 == d2;
}

您说过它应该"匹配列表中的第一项",但您的代码示例只是将其标记为true。如果你特别想知道哪一项是匹配的,你可以这样做:

var theCodeThatMatches = codesList.First(code => code.Contains("255"));
if(theCodeThatMatches == null) return;
//do stuff to theCodeThatMatches

如果这些项目在列表中:

 string codeValue = "255";
 var results = listItems.Where(w => w.Value.IndexOf(codeValue, StringComparison.OrdinalIgnoreCase) >= 0);