Find word(s) between two values in a string

廉价感情. 提交于 2019-11-30 07:43:46

This is a simple extension method I use:

public static string Between(this string src, string findfrom, string findto)
{
    int start = src.IndexOf(findfrom);
    int to = src.IndexOf(findto, start + findfrom.Length);
    if (start < 0 || to < 0) return "";
    string s = src.Substring(
                   start + findfrom.Length, 
                   to - start - findfrom.Length);
    return s;
}

With this you can use

string valueToFind = sourceString.Between("car=", "</value>")

You can also try this:

public static string Between(this string src, string findfrom, 
                             params string[] findto)
{
    int start = src.IndexOf(findfrom);
    if (start < 0) return "";
    foreach (string sto in findto)
    {
        int to = src.IndexOf(sto, start + findfrom.Length);
        if (to >= 0) return
            src.Substring(
                       start + findfrom.Length,
                       to - start - findfrom.Length);
    }
    return "";
}

With this you can give multiple ending tokens (their order is important)

string valueToFind = sourceString.Between("car=", ";", "</value>")

You could use regex

var input = "car= (data between here I want) ;";
var pattern = @"car=\s*(.*?)\s*;"; // where car= is the first delimiter and ; is the second one
var result = Regex.Match(input, pattern).Groups[1].Value;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!