Find word(s) between two values in a string
Asked Answered
L

2

3

I have a txt file as a string, and I need to find words between two characters and Ltrim/Rtrim everything else. It may have to be conditional because the two characters may change depending on the string.

Example:

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

Code:

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

if (pos >= 0)
{
     server = st.Substring(0, pos);..............
}
Longterm answered 10/11, 2011 at 15:38 Comment(1)
You want everything between 2 delimeters, but the delimeters can change? What happens if 2 different types of delimeters appear?Writeup
C
16

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>")
Copolymer answered 10/11, 2011 at 15:43 Comment(0)
C
15

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;
Cuisse answered 10/11, 2011 at 15:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.