0

I have a string from INI file like this below.

string inistr = "[sectionA]KeyName_1=10.01\r\nKeyName_2=20.2\r\nKeyName_3=15.6\r\n[sectionB]KeyName_4=10.01\r\nKeyName_5=20.2\r\nKeyName_6=15.6\r\n"

Then first I try to split into 2 sections by regex and I had tried this regex and gotten the result below from here.

enter image description here

Next, I started to try it by C# and I used Regex.Matches to realize it.

var sections = Regex.Matches(inistr, @"^\[.*\](\r|\n|\r\n)[a-zA-Z0-9_=.\r\n]*");

if(sections.Count != 0)
{
    foreach(var sect in sections)
        Console.WriteLine(sect.ToString());
}
else
    Console.WriteLine("Cannot Find Any Section...");

However, I found it could not find any section by the regex pattern.

Then I found the pattern could get sections if I didn't use '^', like below.

//var sections = Regex.Matches(inistr, @"^\[.*\](\r|\n|\r\n)[a-zA-Z0-9_=.\r\n]*");
var sections = Regex.Matches(inistr, @"\[.*\](\r|\n|\r\n)[a-zA-Z0-9_=.\r\n]*");

But I don't know why it coundn't catch sections if I used '^'.

Why are the results different between C# and here?

Yash Chitroda
  • 645
  • 4
  • 8
  • 27
Verizz
  • 108
  • 1
  • 7
  • 1
    Your online tool is using the PHP variant of regex, which is different from the C# variant. If you want to test a regex, you need to use a .NET-compatible tool. See duplicate. – Peter Duniho Jul 06 '21 at 02:38
  • i tried your code, but no matter `^` exists or not, no match. and why not use some ini package to parse? – Lei Yang Jul 06 '21 at 02:39

1 Answers1

2

Use the RegexOptions.Multiline option so that ^ matches at the beginning of a line (instead of the beginning of the string). So your matching code should be like:

var sections = Regex.Matches(
    inistr, @"^\[.*\](\r|\n|\r\n)[a-zA-Z0-9_=.\r\n]*", RegexOptions.Multiline
);
JosephDaSilva
  • 1,107
  • 4
  • 5