Arto Uusikangas
Arto Uusikangas

Reputation: 1909

C# Regular expression search gives false

I am trying to do a program that searches for certain tags inside textfiles and see if there is text in between those tags. Example of tags below.

--<UsrDef_Mod_Trigger_repl_BeginMod>
--<UsrDef_Mod_Trigger_repl_EndMod>

So i want to search for --<UsrDef_Mod_ and _Begin or _End

I made these RegExp, but i get false on every single one.

if (Regex.Match(line, @"/--<UsrDef_Mod_.*_BeginMod>/g", RegexOptions.None).Success)
else if (Regex.Match(line, @"/--<UsrDef_Mod_.*_EndMod>/g", RegexOptions.None).Success)

So any help to find where im going wrong. I have used regexr.com to check my regexp and its getting a match there but not in C#.

Upvotes: 1

Views: 119

Answers (3)

Thrawn
Thrawn

Reputation: 224

if (Regex.Match(line, @"--<UsrDef_Mod_.*_BeginMod>", RegexOptions.None).Success)
if (Regex.Match(line, @"--<UsrDef_Mod_.*_EndMod>", RegexOptions.None).Success)

Those both get a match - you just remove the /-- and /g options - As per Henk Holtermann´s Answer - a comparison of perl and c# regex options on SO - for further reference.

Upvotes: 2

Nisus
Nisus

Reputation: 824

var matches = Regex.Matches(text, @"<UsrDef_Mod_([a-zA-Z_]+)_BeginMod>([\s\S]+?)<UsrDef_Mod_\1_EndMod>");
if (matches != null)
    foreach (Match m in matches)
        Console.WriteLine(m.Groups[2].Value);

Group #2 will contain the text inside two tags.

Upvotes: 0

Henk Holterman
Henk Holterman

Reputation: 273274

The .NET library Regex doesn't understand the "/ /g"wrapper.

Just remove it:

// Regex.Match(line, @"/--<UsrDef_Mod_.*_BeginMod>/g", 
   Regex.Match(line, @"--<UsrDef_Mod_.*_BeginMod>", 

Upvotes: 4

Related Questions