Skip to main content
 首页 » 编程设计

c#之正则表达式不正确的输出

2024年01月26日26tuyile006

大家好,我正在尝试在 C# 中创建一个正则表达式函数,它将在一个句子中搜索所有以“es”结尾的单词。我试图让输出的格式为

Word1 = bes 
Word2 = mes 
Word3 = ces 

等等。问题是我在编译时不断收到“errorCS0136”。我尝试使用 Console.WriteLine() 并在循环的每次迭代中增加一个计数器变量,但这行不通。这是我收到的错误的副本。非常感谢。

Task1.cs(66,52): error CS1026: Unexpected symbol ',', expecting ')'

Task1.cs(66,55): error CS0136: A local variable named 'match' cannot be declared in this scope because it would give a different meaning to 'match', which is already used in a 'parent or current' scope to denote something else

Task1.cs(66,59): error CS1026: Unexpected symbol ')', expecting ')'

Compilation failed: 3 error(s), 0 warnings

下面是我的源代码。

public void numPatternSearch(){ 
    string input3; 
    string pattern = @"\b\w+es\b"; 
    //Regex regex = new Regex("[*]"); 
    Console.WriteLine("Enter string to search: "); 
    input3 = Console.ReadLine(); 
    //input3 = string.Join("", input3.Where(char.IsDigit).ToArray()); 
    //input3 = Regex.Match(input3, @"\d+").Value; 
    //string[] substrings = regex.Split(input3); 
    foreach (Match match in Regex.Matches(input3, pattern)){ 
        int count = 1; 
        string[] substrings = "Number"+count+" = '{0}'", match; 
        count++; 
        Console.WriteLine(substrings); 
        } 
    //Console.WriteLine(input3); 
    } 
}  

请您参考如下方法:

您的编译器错误发生在该行:

string[] substrings = "Number"+count+" = '{0}'", match; 

这不是有效的 c#。如果你想要结果字符串的列表,你可以试试这个:

List<string> substrings = new List<string>(); 
int count = 1; 
foreach (Match match in Regex.Matches(input3, pattern)) 
{ 
    string substring = string.Format("Number{0} = '{1}'", count, match); 
    count++; 
    Console.WriteLine(substring); 
    substrings.Add(substring); 
 } 

您现在可以使用 substrings进行进一步的操作。您可以转换 List<string>进入数组使用

string[] subStringArray = substrings.ToArray(); 

请注意,我声明了 count在循环之外。否则你会一直使用 1作为伯爵!