【问题标题】:Find word(s) between two values in a string在字符串中的两个值之间查找单词
【发布时间】:2011-12-26 07:05:33
【问题描述】:

我有一个 txt 文件作为字符串,我需要找到两个字符之间的单词以及 Ltrim/Rtrim 其他所有内容。它可能必须是有条件的,因为这两个字符可能会根据字符串而改变。

例子:

car= (data between here I want) ;
car =  (data between here I want) </value>

代码:

int pos = st.LastIndexOf("car=", StringComparison.OrdinalIgnoreCase);

if (pos >= 0)
{
     server = st.Substring(0, pos);..............
}

【问题讨论】:

  • 您想要 2 个分隔符之间的所有内容,但分隔符可以更改?如果出现 2 种不同类型的分隔符会怎样?

标签: c# .net string substring indexof


【解决方案1】:

这是我使用的一个简单的扩展方法:

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

有了这个,你可以使用

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

你也可以试试这个:

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 "";
}

这样你可以给多个结束标记(它们的顺序很重要)

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

【讨论】:

    【解决方案2】:

    你可以使用正则表达式

    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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-13
      • 1970-01-01
      • 2015-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-28
      相关资源
      最近更新 更多