How to get a section Name in an Ini file using RegEx

Viewed 217

I am using this RegEx below to extract the Name of a section in an Ini file.

^\s*\[([a-z_][0-9])\]\s*

but I cannot get it to find a match even on a simple line like

[Compiler]
Path=C:\ProgramFiles (x86)\ProtonIDE\PDS
Database=C:\Program Files (x86)\ProtonIDE

What am I missing?

2 Answers

This part in the pattern [a-z_][0-9] Matches 2 characters, 1 character being either a-z or _, and the second character being a digit.

You could make 1 character class out of it and repeat it 1+ more times. If you want to match uppercase chars, you can make the pattern case insensitive or add [A-Z] to it.

Then you might also shorten it to \w

^\s*\[(\w+)\]

Regex demo

Note that \s also matches a newline. You could also use \h* to match 0+ horizontal whitespace characters.

You could use the pattern '^\[\w+\]$' to get the sections as:

  with TStringList.Create do
    try
      Add('[Compiler]');
      Add('Path=C:\ProgramFiles (x86)\ProtonIDE\PDS');
      Add('Database=C:\Program Files (x86)\ProtonIDE)');
      with TPerlRegEx.Create do
        try
          Options:= [preMultiLine];
          Subject:= Text;
          RegEx:= '^\[\w+\]$';
          while MatchAgain do
            ShowMessage(MatchedText);
            // or ShowMessage(MatchedText.Replace('[', '').Replace(']', '')); if you wish to
        finally
          Free;
        end;
    finally
      Free;
    end;

While the simplest way is to use ReadSections() method of TMemIniFile

  with TMemIniFile.Create('YourIniFile') do
    try
      ReadSections(Memo1.Lines);
    finally
      Free;
    end;
Related