如何提取位于两个指示符之间的文本



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

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

如何循环字符串并找到所有合并字段,以便用文本替换字段?

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

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

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));

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

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

正如@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();
    }
}

最新更新