You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#使用Regex校验用户输入是否匹配指定字符串数组的代码补全求助

C# 正则实现指定饮品名称校验代码方案

原有代码问题说明

  • 错误覆盖用户输入变量Userchoice,导致丢失了待校验的用户输入内容
  • 正则匹配参数顺序颠倒,未正确使用规则校验输入
  • 循环逻辑错误,仅保留最后一个数组元素的匹配结果,无法正确判断是否命中允许列表
  • 数组中Cappuccino拼写错误,少写了一个字母c

修正后完整代码

using System;
using System.Text.RegularExpressions;

namespace RegularExpression
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter the user choice input");
            string Myinput = Console.ReadLine();

            // 修正Cappuccino的拼写错误
            string[] arrayy = new string[4] { "Cappuccino", "Tea", "Milk", "Espresso" };
            MyChoice obj = new MyChoice();
            bool ans = obj.MyChoiceContains(Myinput, arrayy);

            // 输出结果并处理非法输入提示
            if (ans)
            {
                Console.WriteLine("valid");
            }
            else
            {
                Console.WriteLine("invalid:输入值不在允许的列表范围内");
                // 如需抛出异常可以打开下面注释
                // throw new ArgumentException("输入值不在允许的列表范围内");
            }
            Console.ReadKey();
        }
    }
    public class MyChoice
    {
        public bool MyChoiceContains(string Userchoice, string[] myChoiceValues)
        {
            // 空输入直接返回非法
            if (string.IsNullOrWhiteSpace(Userchoice) || myChoiceValues == null || myChoiceValues.Length == 0)
            {
                return false;
            }
            // 将允许的列表拼接为正则或规则,^和$限制完整匹配
            string regexPattern = $"^({string.Join("|", myChoiceValues)})$";
            // 如需不区分大小写校验,可添加RegexOptions.IgnoreCase参数
            return Regex.IsMatch(Userchoice, regexPattern);
        }
    }
}

实现说明

  • 正则规则用^和$包裹,确保用户输入必须和允许的列表项完全匹配,避免部分匹配的误判
  • 将所有允许的选项用|拼接为正则的或分组,一次匹配即可得到结果,无需循环遍历
  • 增加了空输入、空数组的边界校验,避免运行时报错
  • 严格遵守方法限制,MyChoiceContains中未使用任何Console相关方法

内容的提问来源于stack exchange,提问作者RAJESH VARMA R

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 18:48:03