Get string between two strings in a string

2019-01-01 06:03发布

I have a string like:

"super exemple of string key : text I want to keep - end of my string"

I want to just keep the string which is between "key : " and " - ". How can I do that? Must I use a Regex or can I do it in another way?

标签: c# regex string
16条回答
不再属于我。
2楼-- · 2019-01-01 06:19

You already have some good answers and I realize the code I am providing is far from the most efficient and clean. However, I thought it might be useful for educational purposes. We can use pre-built classes and libraries all day long. But without understanding the inner-workings, we are simply mimicking and repeating and will never learn anything. This code works and is more basic or "virgin" than some of the others:

char startDelimiter = ':';
char endDelimiter = '-';

Boolean collect = false;

string parsedString = "";

foreach (char c in originalString)
{
    if (c == startDelimiter)
         collect = true;

    if (c == endDelimiter)
         collect = false;

    if (collect == true && c != startDelimiter)
         parsedString += c;
}

You end up with your desired string assigned to the parsedString variable. Keep in mind that it will also capture proceeding and preceding spaces. Remember that a string is simply an array of characters that can be manipulated like other arrays with indices etc.

Take care.

查看更多
琉璃瓶的回忆
3楼-- · 2019-01-01 06:22

A working LINQ solution:

string str = "super exemple of string key : text I want to keep - end of my string";
string res = new string(str.SkipWhile(c => c != ':')
                           .Skip(1)
                           .TakeWhile(c => c != '-')
                           .ToArray()).Trim();
Console.WriteLine(res); // text I want to keep
查看更多
不再属于我。
4楼-- · 2019-01-01 06:23

You can do it without regex

 input.Split(new string[] {"key :"},StringSplitOptions.None)[1]
      .Split('-')[0]
      .Trim();
查看更多
无色无味的生活
5楼-- · 2019-01-01 06:27
 string str="super exemple of string key : text I want to keep - end of my string";
        int startIndex = str.IndexOf("key") + "key".Length;
        int endIndex = str.IndexOf("-");
        string newString = str.Substring(startIndex, endIndex - startIndex);
查看更多
皆成旧梦
6楼-- · 2019-01-01 06:27

You can use the extension method below:

public static string GetStringBetween(this string token, string first, string second)
    {            
        if (!token.Contains(first)) return "";

        var afterFirst = token.Split(new[] { first }, StringSplitOptions.None)[1];

        if (!afterFirst.Contains(second)) return "";

        var result = afterFirst.Split(new[] { second }, StringSplitOptions.None)[0];

        return result;
    }

Usage is:

var token = "super exemple of string key : text I want to keep - end of my string";
var keyValue = token.GetStringBetween("key : ", " - ");
查看更多
情到深处是孤独
7楼-- · 2019-01-01 06:29

or, with a regex.

using System.Text.RegularExpressions;

...

var value =
    Regex.Match(
        "super exemple of string key : text I want to keep - end of my string",
        "key : (.*) - ")
    .Groups[1].Value;

with a running example.

You can decide if its overkill.

or

as an under validated extension method

using System.Text.RegularExpressions;

public class Test
{
    public static void Main()
    {
        var value =
                "super exemple of string key : text I want to keep - end of my string"
                    .Between(
                        "key : ",
                        " - ");

        Console.WriteLine(value);
    }
}

public static class Ext
{
    static string Between(this string source, string left, string right)
    {
        return Regex.Match(
                source,
                string.Format("{0}(.*){1}", left, right))
            .Groups[1].Value;
    }
}
查看更多
登录 后发表回答