寻找附在[[]]中的字符串键 [英] Finding keys in string enclosed with [[ ]]

查看:115
本文介绍了寻找附在[[]]中的字符串键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有有之间的[[]]一些关键字符串

I have a string which has some keys between [[]].

 string s = "<p>Hi [[USER]],<br/>How are you doing<br/>Regards,<br/>[[SENDER]]</p>";



我想先取中对此我tyring通过做一个列表中的键名用户和发件人

I want to first fetch the key names USER and SENDER in a list which i am tyring to do by:

 var keys = new List<string>();
        foreach (Match match in Regex.Matches(s, @"[[(.*?)]]")) 
        {
            keys.Add(match.Value);
        }



不过,该键来了空。

However, The keys are coming empty.

谁能告诉我什么,我做错了。

Can anyone tell me what I'm doing wrong?

另外,我尝试使用<< >>而不是[[]]这是工作,但是当我将数据加载到<字消失;< >>

Also, I tried using << >> instead of [[ ]] which is working but words disappear when I load data into << >>

推荐答案

看来你需要逃避'[':

It seems you need to escape '[':

string s = "<p>Hi [[USER]],<br/>How are you doing<br/>Regards,<br/>[[SENDER]]</p>";

var keys = new List<string>();
foreach (Match match in Regex.Matches(s, @"\[\[(.*?)]]"))
{
    keys.Add(match.Value.Trim('[').Trim(']'));
}

要排除 [[]] 不修剪,使用 @(小于?= \ [\ [)(。*?)(?=])

或者像@ Wiktor的-stribiżew指出的那样,你可以简化为:

Or as @wiktor-stribiżew pointed out, you can simplify that to be:

var keys = Regex.Matches(s, @"\[\[(.*?)]]").Cast<Match>()
                                          .Select(p => p.Groups[1].Value).ToList()

这篇关于寻找附在[[]]中的字符串键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆