简体   繁体   English

如何使用正则表达式从 INI 文件中提取特定值?

[英]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:我有点困惑如何最好地使用正则表达式,希望能得到一些帮助,我想从 INI 文件中提取 URL 值,如下所示:

[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.因此,我可以从正则表达式中获取 URL 值作为唯一匹配项 - 但我对它们的了解还不够(还)无法做到这一点。
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.我已经看到 RegEx 示例将解析任何 INI 文件并获取名称、值对我只想从文件中获取 URL 值,无论它包含什么。
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".这看起来很简单,但我似乎无法创建一个特定的案例 RegEx,我希望从“URL =”到最后的 vbCrLf 的所有内容都是我的“匹配”。
I have refered to Regular-Expressions.info which has been a help before but still cannot get this simple example to work.我曾参考过 Regular-Expressions.info ,它以前一直是一个帮助,但仍然无法让这个简单的例子工作。

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.请注意,这将匹配任何URL=行,无论它位于哪个部分。
If that's not what you want, please tell me.如果那不是你想要的,请告诉我。

EDIT : It should actually be .Groups[ 1 ].Value ;编辑:它实际上应该是.Groups[ 1 ].Value this will not include URL= .这将不包括URL=

The regular expression below matches value on a line after parameterName and equal sign.下面的正则表达式匹配 parameterName 和等号后一行的值。 All spaces and tabs outside parameterName and value are ignored.忽略 parameterName 和 value 之外的所有空格和制表符。 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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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