【问题标题】:To check if an element is present in a string array using "Regex" in c#在 C# 中使用“Regex”检查字符串数组中是否存在元素
【发布时间】:2021-11-04 01:56:12
【问题描述】:

帮助我使用 Regex 完成代码。我是学习 c# 的新手。

创建一个 C# 程序,使用正则表达式完成以下任务

我。创建一个字符串变量'Myinput'并从用户那里读取值

二。检查给定的值是否与以下匹配

  1. 卡布奇诺

  2. 牛奶

  3. 浓缩咖啡

三。如果除上述之外的任何其他值,程序需要抛出错误

消息

using System;
using System.Linq;
using System.Text.RegularExpressions;

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

            string[] arrayy = new string[4] { "Cappucino", "Tea", "Milk", "Espresso" };
            MyChoice obj = new MyChoice();
            bool ans = obj.MyChoiceContains(Myinput, arrayy);

            Console.WriteLine(ans);
            Console.ReadKey();

            /// i. Create a string variable 'Myinput' and read the value from user. 
            /// ii. Check whether the given values are matching with the following 
            ///     1.Cappuccino 2. Tea 3. Milk 4. Espresso. 
            /// iii. If any other values except the above, the program need to throw the error 
            ///message.
            /// Display valid or invalid message here.
        }
    }
    public class MyChoice
    {
        public bool MyChoiceContains(string Userchoice, string[] myChoiceValues)
        {
            Userchoice = @"^[A-Za-z]$";

            Regex rg = new Regex(Userchoice);


            bool ans = true;
            foreach (string s in myChoiceValues)
            {
                ans = Regex.IsMatch(Userchoice, s);
            }
            return ans;

            }

        }
    }
/// <summary>
/// Create Class with Class name 'MyChoice'. 
/// </summary>


/// <summary>
/// Create a method with the name 'MyChoiceContains'.
/// <param name="Userchoice"></param><type>string</type>
/// <param name="myChoiceValues"></param><type>string[]</type>
/// <returns>bool</returns>return "true" if valid else return "false".
/// Note: Please dont use Console.WriteLine() and Console.ReadLine() in this method.
/// </summary>

【问题讨论】:

  • 我看不出正则表达式与您的问题有何关系。您的意思是用户应该能够输入正则表达式并且应该打印所有匹配的元素吗?
  • @Llama 完全正确。
  • 在这种情况下,您面临的问题是什么(除了您硬编码了MyChoiceContains 中的值)?您的问题是您总是退出第一个项目的循环,而不是在第一个项目有效的情况下检查后续项目吗?
  • 我需要检查正则表达式格式的输入字符串是否与任何一个数组元素匹配。如果是,则返回 true,否则返回 false。
  • 请修剪您的代码,以便更容易找到您的问题。请按照以下指南创建minimal reproducible example

标签: c# regex


【解决方案1】:

在 cmets 中,您已声明用户将输入正则表达式,并且您希望检查正则表达式是否与数组中的任何元素匹配。您可以手动执行此操作:

foreach (string s in myChoiceValues)
{
    if (rg.IsMatch(s))
        return true;
}   
return false;

我已将return false; 移到外面,这样当第一项不匹配时您就不会return false;

或者,您可以使用 LINQ 扩展方法执行此操作。您需要确保文件顶部有 using System.Linq;

return myChoiceValues.Any(v => rg.IsMatch(v));
// or simply: return myChoiceValues.Any(rg.IsMatch);

您可能还需要重写硬编码的测试表达式 (^[A-Za-z]$),因为目前这需要在字符串的开头和结尾之间使用单个字符(即匹配的字符串应该是单个字符)。也许你的意思是:

^[A-Za-z]+$

+ 表示它将匹配来自 [A-Za-z] 集合的 1 个或多个字符。

【讨论】:

  • @Rajesh 是不是因为我在答案的最后部分概述的问题? Example
  • 如果我在数组中输入除了这四个元素之外的元素,我会得到真实的。那么这里的错误是什么?
  • @RAJESHVARMAR 我想您可能想了解正则表达式的作用。你似乎正在为此苦苦挣扎。 ^[A-Za-z]+$ 确保字符串中的所有字符都来自集合 A-Za-z。就这样。这就是您在问题中所描述的。 Example
【解决方案2】:
  string pattern = @"(Cappuccino | Tea | Milk | Espresso)";
  string input = "text";
  Match m = Regex.Match(input, pattern, RegexOptions.IgnoreCase);
  if (m.Success) 
  {
     // matched
  }
  else
  {
     // not matched
  }

Ressource

【讨论】:

    猜你喜欢
    • 2022-07-30
    • 2012-02-23
    • 2017-01-27
    • 2016-01-17
    • 2013-10-31
    • 2020-11-12
    • 2019-08-06
    • 2021-12-27
    相关资源
    最近更新 更多