如何提取位于两个指标之间的文本?

时间:2015-03-27 14:55:08

标签: c# .net

我有一个包含多个&#34;合并字段的长字符串&#34;,所有合并字段将采用以下格式:<<FieldName>>

该字符串将具有多个不同类型的合并字段,即<<FirstName>><<LastName>>

如何遍历字符串并找到所有合并字段,以便我可以用文本替换字段?

我不会知道字符串中所有不同的Merge字段,用户可以在两个指标之间输入任何内容,即<<Anything>>

理想情况下,我希望远离任何正则表达式,但很乐意探索所有选项。

3 个答案:

答案 0 :(得分:5)

RegularExpression在这里最有意义

string text = "foo <<FieldName>> foo foo <<FieldName>> foo";
string result = Regex.Replace(text, @"[<]{2}\w*[>]{2}", "bar", RegexOptions.None);
没有RegEx的

更新 - 问题得到更新后:

Dictionary<string, string> knownFields = new Dictionary<string, string> {    {"<<FirstName>>", "Jon"},    {"<<LastName>>", "Doe"},    {"<<Job>>", "Programmer"}};
string text = "Hello my name is <<FirstName>> <<LastName>> and i work as a <<Job>>";
knownFields.ToList().ForEach(x => text = text.Replace(x.Key, x.Value));

答案 1 :(得分:1)

我知道你说你想避免正则表达式,但它是适合这项工作的工具。

Dictionary<string,string> fieldToReplacement = new Dictionary<string,string> {
    {"<<FirstName>>", "Frank"},
    {"<<LastName>>", "Jones"},
    {"<<Salutation>>", "Mr."}
};

string text = "Dear <<Salutation>> <<FirstName>> <<LastName>>, thanks for using RegExes when applicable. You're the best <<FirstName>>!!";
string newText = Regex.Replace(text, "<<.+?>>", match => {
    return fieldToReplacement[match.Value];
});

Console.WriteLine(newText);

https://dotnetfiddle.net/HPfHph

答案 2 :(得分:-3)

正如@Alex K.所写,您需要搜索开始和结束标记的索引,如下所示:

class Program {
    static void Main(string[] args) {
        string text = "<<FieldName>>";
        const string startTag = "<<";
        const string endTag = ">>";
        int offset = 0;
        int startIndex = text.IndexOf(startTag, offset);
        if(startIndex >= 0) {
            int endIndex = text.IndexOf(endTag, startIndex + startTag.Length);
            if(endIndex >= 0) {
                Console.WriteLine(text.Substring(startIndex + startTag.Length, endIndex - endTag.Length));
                //prints "FieldName"
            }
        }
        Console.ReadKey();
    }
}
相关问题