问题描述
class Program
{
static void Main(string[] args)
{
string[] lines = System.IO.File.ReadAllLines("C:\\Users\\mrazekd\\Downloads\\PrubehPripravyPat.txt");
string regMatch = "***";
foreach (string line in lines)
{
if (Regex.IsMatch (line,regMatch))
{
Console.WriteLine("found\n");
}
else
{
Console.WriteLine("not found\n");
}
}
}
}
此代码仅查找数字或字母,但未找到星号之类的符号。我在做什么错?在我的文件中有很多星星,但是它仍然找不到,并且列出了未指定搜索值的错误。
解决方法
您必须使用@和\对其进行转义,请参见此处:https://www.codeproject.com/Articles/371232/Escaping-in-Csharp-characters-strings-string-forma
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main(string[] args)
{
string[] lines = System.IO.File.ReadAllLines("C:\\Users\\mrazekd\\Downloads\\PrubehPripravyPat.txt");
string regMatch = @"\*";
foreach (string line in lines)
{
if (Regex.IsMatch (line,regMatch))
{
Console.WriteLine("found\n");
}
else
{
Console.WriteLine("not found\n");
}
}
}
}