从字符串c#中捕获字符串

时间:2015-04-23 19:43:43

标签: c# regex string formatting substring

我需要格式化用户输入的一些文字。

例如:string str = "{{Lorem Ipsum|bold}}"只是印刷和排版行业的虚拟文本。

我使用IndexOf从字符串中提取Lorem Ipsum并以粗体显示。但如果我有两个单词格式化相同的字符串,则面临问题。

例如:string str ="{{Lorem Ipsum|bold}}"只是"{{printing|blue}}"和排版行业的虚拟文字。

有人可以帮助我使用任何正则表达式模式将{{Lorem Ipsum|bold}}{{printing|blue}}解压缩为c#中的数组。

注意:模式有时可能是{{printing|blue,bold,http://www.google.com}}

格式化的扩展方法。我有硬编码进行测试,之后我会相应地进行优化。

public static string Format(this string value)
    {
        System.Uri uriResult = null;
        bool result = false;
        string path = ConfigurationManager.AppSettings["path"];
        if (value.Length > 0)
        {
            if (value.Contains("{{") && value.Contains("|") && value.Contains("}}"))
            {
                int totalLength = value.Length;
                string unformattedText = value.Substring(value.IndexOf("{{"), (value.IndexOf("}}") - value.IndexOf("{{")) + 2);
                string flowersRemoved = unformattedText.Substring(0, unformattedText.Length - 2);
                flowersRemoved = flowersRemoved.Substring(2, flowersRemoved.Length - 2);
                string[] textFormats = flowersRemoved.Split('|');
                string text = textFormats[0];
                string[] formats = textFormats[1].Split(',');
                foreach (string format in formats)
                {
                    result = Uri.TryCreate(format.ToLower(), UriKind.Absolute, out uriResult) && uriResult.Scheme == Uri.UriSchemeHttp;
                    if (format.ToLower() == "bold")
                        text = "<b>" + text + "</b>";
                    else if (format.ToLower() == "red")
                        text = "<font color = \"red\">" + text + "</font>";
                    else if (format.ToLower() == "blue")
                        text = "<font color = \"blue\">" + text + "</font>";
                    else if (result)
                        text = "<a href = \"" + format + "\" target = \"_blank\">" + text + "</a>";
                    else if (System.IO.File.Exists(path + format))
                    {
                        string fileName = System.IO.Path.GetFileName(path + format);
                        text = "<a href = \" \\s\\Download\\" + fileName + "\">" + text + "</a>";
                    }
                }

                value = value.Replace(unformattedText, text);

            }
            return value;
        }
        return value;
    }

2 个答案:

答案 0 :(得分:1)

  

模式有时可能是{{printing|blue,bold,http://www.google.com}}

尝试Split

The following fiddle使用Split()而非正则表达式,因为正则表达式往往难以阅读。结果key字符串包含要格式化的单词,values字符串数组包含相关设置。

string str = "{{printing|blue,bold,http://www.google.com}}";

// get your settings
int pFrom = str.IndexOf("{{") + "{{".Length;
int pTo = str.LastIndexOf("}}");
string settings = str.Substring(pFrom, pTo - pFrom);

// split 
string[] parts = settings.Split('|');
string key = parts[0];
string[] values = parts[1].Split(',');

// for demo purposes only
Console.WriteLine(key);
foreach(var v in values)
{
    Console.WriteLine("-" + v);
}

输出

printing
-blue
-bold
-http://www.google.com

如果你最后说明这一点,你可以得到你想要的HTML:

// create html
var html = string.Format(@"
<a href='{3}' target ='_blank'>
    <font color='{1}'>
        <b>{0}</b>
    </font>
</a>", key, values[0], values[1], values[2]);

Console.WriteLine(html);

输出

<a href ='http://www.google.com' target = '_blank'>
    <font color ='blue'>
        <b>printing</b>
    </font>
</a>

Watch it run here

答案 1 :(得分:1)

您可以使用具有替换功能的下一个regexp

string str = "{{Lorem Ipsum|bold}}";
string path = ConfigurationManager.AppSettings["path"];
var formattedString = Regex.Replace(str, @"{{(?<symbol>[^|]+?)\|(?<formats>.+?)}}", m =>
{
    var formatedPattern = m.Groups["formats"].Value.Split(',').Aggregate("{0}", (acc, f) =>
    {
        switch (f.ToLower())
        {
            case "bold": return "<b>" + acc + "</b>";
            case "red": return "<font color = \"red\">" + acc + "</font>";
            case "blue": return "<font color = \"blue\">" + acc + "</font>";
        };

        Uri uriResult;
        if (Uri.TryCreate(f.ToLower(), UriKind.Absolute, out uriResult) && uriResult.Scheme == Uri.UriSchemeHttp)
        {
            return "<a href = \"" + f + "\" target = \"_blank\">" + acc + "</a>";
        }
        else if (System.IO.File.Exists(path + f))
        {
            string fileName = System.IO.Path.GetFileName(path + f);
            return "<a href = \" \\s\\Download\\" + fileName + "\">" + acc + "</a>";
        }
        return acc;
    });
    return string.Format(formatedPattern, m.Groups["symbol"].Value);
});