简体   繁体   中英

How to extract a particular value from an INI File using a Regular Expression?

I am a bit confused how to best use a Regular Expression and hope I can get some help I want to extract a URL value from an INI File as such:

[DEFAULT]
BASEURL=http://www.stackoverflow.com/
[InternetShortcut]
URL=http://www.stackoverflow.com/

So I can get the URL value as the only Match from the Regular expression - but I don't understand enough about them (yet) to do this.
I have seen RegEx examples that will parse any INI file and get the Name, Value Pairs I just want to get the URL value only from a file no matter what else it contains.
My aim is to have something like this:

Dim _pattern As New Text.RegularExpressions.Regex("RegEx")
Dim _url As String = _pattern.Match(iniContentString).Value

It seems simple but I cannot seem to create a specific case RegEx where I want everything from "URL=" to the vbCrLf at the End to be my "Match".
I have refered to Regular-Expressions.info which has been a help before but still cannot get this simple example to work.

Like this:

New Regex("^URL=(.*)$", RegexOptions.Multiline).Match(iniContent).Groups[1].Value

Note that this will match any URL= line, whatever section it's in.
If that's not what you want, please tell me.

EDIT : It should actually be .Groups[ 1 ].Value ; this will not include URL= .

The regular expression below matches value on a line after parameterName and equal sign. All spaces and tabs outside parameterName and value are ignored. Space followed by a semi-colon begins in-line comment.

var parameterName = "URL";

var regex = new Regex(
    pattern: $@"^[ \t]*{parameterName}[ \t]*=(?:(?:[ \t]+;.*)|(?:[ \t]*(\S.*?)(?:(?: ;.*)|(?:[ \t]+))?))$",
    RegexOptions.Multiline | RegexOptions.IgnoreCase);

var value = regex.Match(_iniContent).Groups[1].Value;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM