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:14

As I always say nothing is impossible:

string value =  "super exemple of string key : text I want to keep - end of my string";
Regex regex = new Regex(@"(key \: (.*?) _ )");
Match match = regex.Match(value);
if (match.Success)
{
    Messagebox.Show(match.Value);
}

Remeber that should add reference of System.Text.RegularExpressions

Hope That I Helped.

查看更多
栀子花@的思念
3楼-- · 2019-01-01 06:14

If you are looking for a 1 line solution, this is it:

s.Substring(s.IndexOf("eT") + "eT".Length).Split("97".ToCharArray()).First()

The whole 1 line solution, with System.Linq:

using System;
using System.Linq;

class OneLiner
{
    static void Main()
    {
        string s = "TextHereTisImortant973End"; //Between "eT" and "97"
        Console.WriteLine(s.Substring(s.IndexOf("eT") + "eT".Length)
                           .Split("97".ToCharArray()).First());
    }
}
查看更多
无与为乐者.
4楼-- · 2019-01-01 06:15

Perhaps, a good way is just to cut out a substring:

String St = "super exemple of string key : text I want to keep - end of my string";

int pFrom = St.IndexOf("key : ") + "key : ".Length;
int pTo = St.LastIndexOf(" - ");

String result = St.Substring(pFrom, pTo - pFrom);
查看更多
与君花间醉酒
5楼-- · 2019-01-01 06:15

Here is the way how i can do that

   public string Between(string STR , string FirstString, string LastString)
    {       
        string FinalString;     
        int Pos1 = STR.IndexOf(FirstString) + FirstString.Length;
        int Pos2 = STR.IndexOf(LastString);
        FinalString = STR.Substring(Pos1, Pos2 - Pos1);
        return FinalString;
    }
查看更多
怪性笑人.
6楼-- · 2019-01-01 06:15
var matches = Regex.Matches(input, @"(?<=key :)(.+?)(?=-)");

This returns only the value(s) between "key :" and the following occurance of "-"

查看更多
萌妹纸的霸气范
7楼-- · 2019-01-01 06:16

Regex is overkill here.

You could use string.Split with the overload that takes a string[] for the delimiters but that would also be overkill.

Look at Substring and IndexOf - the former to get parts of a string given and index and a length and the second for finding indexed of inner strings/characters.

查看更多
登录 后发表回答