转义做了吗?
//创建泛型
List<string> list = new List<string>();
string pattern = "";
//判断是否传入筛选条件 如果没有这选择默认的
if (patterns == null)
{
pattern = @"(\ba/\d{8})/(\b\d{6}).(\bhtm)(?!#)";
}
else
{
pattern = patterns;
}
//筛选 并保存数据
MatchCollection ms = Regex.Matches(FilePath, pattern.Trim());
foreach (Match m in Regex.Matches(FilePath, pattern))
{
list.Add(qianz.Trim() + m.ToString().Trim());
}
return list;
@落幕残情: 试试再拿双斜杠去匹配内容。可能原因是文件内容读入string后斜杠都变成双斜杠了。试试看。
还有,正则表达式其实效率很低的,不这边没必要去匹配两次。别重复计算了
public class MyClass
{
public static void RunSnippet()
{
WL("Start Regex");
string input=string.Empty;
string regex=string.Empty;
string text=string.Empty;
while(!input.Equals("exit"))
{
if(input.StartsWith("regex:"))
regex=input.TrimStart("regex:".ToCharArray());
if(input.StartsWith("text:"))
text=input.TrimStart("text:".ToCharArray());
if(input.Equals("run"))
test(regex,text);
if(input.Equals("display"))
WL("regex:{0} \t\t text:{1}",regex,text);
if(string.IsNullOrEmpty(regex))
WL("Input Regex");
else if(string.IsNullOrEmpty(text))
WL("Input Text");
else
WL("Run or Change");
WL("-------------------------");
input=RL();
}
}
public static void test(string r,string t)
{
WL("Matching......");
if(Regex.IsMatch(t,r))
{
WL("Match True");
var m=Regex.Matches(t,r);
WL(">>>>>>>>>>>>>>>>>>");
for(int i=0;i<m.Count;i++)
{
WL("{0}、\t\t{1}",i,m[i].Value);
}
WL(">>>>>>>>>>>>>>>>>>");
}
WL("Run End");
}
#region Helper methods
public static void Main()
{
try
{
RunSnippet();
}
catch (Exception e)
{
string error = string.Format("---\nThe following error occurred while executing the snippet:\n{0}\n---", e.ToString());
Console.WriteLine(error);
}
finally
{
Console.Write("Press any key to continue...");
Console.ReadKey();
}
}
private static void WL(object text, params object[] args)
{
Console.WriteLine(text.ToString(), args);
}
private static string RL()
{
return Console.ReadLine();
}
private static void Break()
{
System.Diagnostics.Debugger.Break();
}
#endregion
}
自己随便写的,你放控制台里跑一下。貌似正则不对。