【发布时间】:2021-11-04 01:56:12
【问题描述】:
帮助我使用 Regex 完成代码。我是学习 c# 的新手。
创建一个 C# 程序,使用正则表达式完成以下任务
我。创建一个字符串变量'Myinput'并从用户那里读取值
二。检查给定的值是否与以下匹配
-
卡布奇诺
-
茶
-
牛奶
-
浓缩咖啡
三。如果除上述之外的任何其他值,程序需要抛出错误
消息
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。