簡體   English   中英

如何檢查字符串是否包含給定字符列表之外的字符

[英]How to check if a string contains chars that are outside of a given char list

我有一個字符串,我需要檢查此字符串是否包含給定列表中沒有的任何字符。

假設我已允許使用chars new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' , '.'}

如果字符串是“ 54323.5”-可以!

如果字符串是“ 543g23.5”-這將是不可能的,因為它包含不在允許的字符列表中的“ g”。

空字符串被視為無效。

我正在嘗試通過使用“ IndexOfAny()”來實現這一目標,但到目前為止還沒有運氣。 當然,將所有不允許的字符傳遞給此方法將不是解決方案。

請注意,允許的字符列表可能會更改,並且基於列表更改來更改驗證算法不被視為解決方案。

對於那些問我嘗試過的代碼的人,這里是:

        private bool CheckInvalidInput(string stringToCheck)
    {
        char[] allowedChars = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };

        var chars = Enumerable.Range(0, char.MaxValue + 1)
                  .Select(i => (char)i)
                  .ToArray();

        var unallowedChars = chars.Except(allowedChars).ToArray();

        bool validString = true;
        if(stringToCheck.IndexOfAny(unallowedChars) != -1)
        {
            validString = false;
        }

        return validString;
    }

希望您會找到更好的解決方案:D。

可以使用非常簡單的模式來完成。 Regex.IsMatch(yourString, @"^[\\d.]+$");

^是行的開頭

[\\d.]+匹配一個或多個字符( .0-9

$是行的結尾

演示版

編輯:這也將匹配.

如果不希望出現這種情況,請嘗試使用此^(?=\\d)[\\d.]+$

這很容易實現。 string類型實現IEnumerable<char> ,因此您可以使用LINQ All方法來檢查其所有字符是否都滿足謂詞。 對於您的情況,謂詞是每個字符都包含在allowedChars集合中,因此可以使用Contains方法:

private static bool CheckInvalidInput(string stringToCheck, IEnumerable<char> allowedChars)
{
    return stringToCheck.All(allowedChars.Contains);
}

如果您的allowedChars設置變大,則需要將其轉換為HashSet<char>以獲得更好的性能。

完整示例:

using System;
using System.Linq;
using System.Collections.Generic;

public class Test
{
    public static void Main()
    {
        // var allowedChars = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.' };
        var allowedChars = "0123456789.";

        Console.WriteLine(CheckInvalidInput("54323.5", allowedChars));   // True
        Console.WriteLine(CheckInvalidInput("543g23.5", allowedChars));  // False
    }

    private static bool CheckInvalidInput(string stringToCheck, IEnumerable<char> allowedChars)
    {
        return stringToCheck.All(allowedChars.Contains);
    }
}

如果允許的字符數組是動態的,則可以創建將接受允許的字符數組並動態構造模式的過程。 請注意,您必須轉義某些字符才能在Regex中使用:

static void TestRegex(char[] check_chars)
{
    string[] inputs = { "54323.5", "543g23.5" };
    var check_chars2 = check_chars.Select(c => Regex.Escape(c.ToString()));
    string pattern = "^(" + string.Join("|", check_chars2) + ")+$";
    foreach (string input in inputs)
    {
        WriteLine($"Input {input} does{(Regex.IsMatch(input, pattern) ? "" : " not")} match");
    }
}

// Output:
// Input 54323.5 does match
// Input 543g23.5 does not match

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM