[英]Umbraco macro string into KeyValuePair
I have a string that looks like this: 我有一个看起来像这样的字符串:
<?UMBRACO_MACRO redirectto="/sagen.aspx" loginpage="/Login.aspx" macroAlias="BrowserValidation" />
I want to get a list of KeyValuePair<string, string>
where the key is the first part and value is the second part. 我想获取
KeyValuePair<string, string>
的列表,其中键是第一部分,值是第二部分。 An example would be: 一个例子是:
Im thinking of using regular expressions but to be honest I don't where to start. 我正在考虑使用正则表达式,但老实说我没有从哪里开始。 I know I can use
\\"(.*?)\\"
to get the values, but I don't know how to get the keys. 我知道我可以使用
\\"(.*?)\\"
来获取值,但是我不知道如何获取键。
... Try this: ... 尝试这个:
\s(?<key>.*?)\=\"(?<value>.*?)\"
Basically, this will give you 2 named captures: 基本上,这将为您提供2个命名捕获:
="
is encountered ="
"
is encountered "
之前,它将是任意数量的字符 And your output would be: 您的输出将是:
key: redirectto || value: /sagen.aspx
key: loginpage || value: /Login.aspx
key: macroAlias || value: BrowserValidation
Hope this does the trick!! 希望这能解决问题!!
You can try the following regex: 您可以尝试以下正则表达式:
(?<=\s)([^=]+)="([^"]+)"
Here is the code in C#: 这是C#中的代码:
var input = @"<?UMBRACO_MACRO redirectto=""/sagen.aspx"" loginpage=""/Login.aspx"" macroAlias=""BrowserValidation"" />";
var matches = Regex.Matches(input, @"(?<=\s)([^=]+)=""([^""]+)""");
foreach (Match match in matches) {
Console.Write(match.Groups[1].Value);
Console.Write(" : ");
Console.WriteLine(match.Groups[2].Value);
}
and here is a more compact version of the previous code which automatically maps attributes name and value pair to a dictionary: 这是前面代码的更紧凑版本,该代码自动将属性名称和值对映射到字典:
var input = @"<?UMBRACO_MACRO redirectto=""/sagen.aspx"" loginpage=""/Login.aspx"" macroAlias=""BrowserValidation"" />";
var matches = Regex.Matches(input, @"(?<=\s)([^=]+)=""([^""]+)""");
var dictionary = matches.Cast<Match>()
.Select( m => new {Key = m.Groups[1].Value, Value = m.Groups[2].Value } )
.ToDictionary(pair => pair.Key, pair => pair.Value);
Console.WriteLine(dictionary);
How about: 怎么样:
static void Main()
{
string stringToSearch = @"<?UMBRACO_MACRO redirectto=""/sagen.aspx"" loginpage=""/Login.aspx"" macroAlias=""BrowserValidation"" />";
string pattern = @"\s(\S+)=""(.+?)""";
var matches = Regex.Matches( stringToSearch, pattern );
foreach( Match match in matches )
{
Console.WriteLine( "Key: " + match.Groups[1].ToString() + ". Value: " + match.Groups[2].ToString() );
}
}
Output: 输出:
Key: redirectto.
密钥:redirectto。 Value: /sagen.aspx
值:/sagen.aspx
Key: loginpage.
密钥:登录页面。 Value: /Login.aspx
值:/Login.aspx
Key: macroAlias.
关键:macroAlias。 Value: BrowserValidation
值:BrowserValidation
where: 哪里:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.