1

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#.

Arto Uusikangas
  • 1,889
  • 5
  • 20
  • 33
  • 1
    you can just try out yourself, e.g. here: http://regexstorm.net/tester. BTW Instead of Regex.Match(...).Success you may as well use Regex.IsMatch – CHS Jun 02 '17 at 09:07
  • 1
    not trying to avoid the problem here, but a possible solution would be: line.substring(line.indexOf("-- – Gabri T Jun 02 '17 at 09:11

3 Answers3

4

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>", 
H H
  • 263,252
  • 30
  • 330
  • 514
  • I just realized this myself by using the regexstorm.net/tester. After trying everything i removed them for the heck of it and it worked.. but thx. – Arto Uusikangas Jun 02 '17 at 09:12
2
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.

Thrawn
  • 214
  • 5
  • 12
0
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.

Nisus
  • 804
  • 7
  • 11