development

문자열에서 두 문자열 사이의 문자열 가져 오기

big-blog 2020. 9. 8. 21:35
반응형

문자열에서 두 문자열 사이의 문자열 가져 오기


다음과 같은 문자열이 있습니다.

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

"key : "사이에있는 문자열을 유지하고 싶습니다 " - ". 어떻게 할 수 있습니까? 정규식을 사용해야합니까 아니면 다른 방법으로 수행 할 수 있습니까?


아마도 좋은 방법은 하위 문자열 을 잘라내는 것입니다 .

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

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

또는 문자열 연산만으로

var start = input.IndexOf("key : ") + 6;
var match2 = input.Substring(start, input.IndexOf("-") - start);

정규식없이 할 수 있습니다.

 input.Split(new string[] {"key :"},StringSplitOptions.None)[1]
      .Split('-')[0]
      .Trim();

구현이 얼마나 강력하고 유연한 지에 따라 실제로는 약간 까다로울 수 있습니다. 내가 사용하는 구현은 다음과 같습니다.

public static class StringExtensions {
    /// <summary>
    /// takes a substring between two anchor strings (or the end of the string if that anchor is null)
    /// </summary>
    /// <param name="this">a string</param>
    /// <param name="from">an optional string to search after</param>
    /// <param name="until">an optional string to search before</param>
    /// <param name="comparison">an optional comparison for the search</param>
    /// <returns>a substring based on the search</returns>
    public static string Substring(this string @this, string from = null, string until = null, StringComparison comparison = StringComparison.InvariantCulture)
    {
        var fromLength = (from ?? string.Empty).Length;
        var startIndex = !string.IsNullOrEmpty(from) 
            ? @this.IndexOf(from, comparison) + fromLength
            : 0;

        if (startIndex < fromLength) { throw new ArgumentException("from: Failed to find an instance of the first anchor"); }

            var endIndex = !string.IsNullOrEmpty(until) 
            ? @this.IndexOf(until, startIndex, comparison) 
            : @this.Length;

        if (endIndex < 0) { throw new ArgumentException("until: Failed to find an instance of the last anchor"); }

        var subString = @this.Substring(startIndex, endIndex - startIndex);
        return subString;
    }
}

// usage:
var between = "a - to keep x more stuff".Substring(from: "-", until: "x");
// returns " to keep "

내가 할 수있는 방법은 다음과 같습니다.

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

여기서 정규식은 과잉입니다.

당신은 할 수 사용 string.Split걸리는 과부하 string[]구분 기호에 대한하지만 것 또한 과잉합니다.

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.


I think this works:

   static void Main(string[] args)
    {
        String text = "One=1,Two=2,ThreeFour=34";

        Console.WriteLine(betweenStrings(text, "One=", ",")); // 1
        Console.WriteLine(betweenStrings(text, "Two=", ",")); // 2
        Console.WriteLine(betweenStrings(text, "ThreeFour=", "")); // 34

        Console.ReadKey();

    }

    public static String betweenStrings(String text, String start, String end)
    {
        int p1 = text.IndexOf(start) + start.Length;
        int p2 = text.IndexOf(end, p1);

        if (end == "") return (text.Substring(p1));
        else return text.Substring(p1, p2 - p1);                      
    }

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

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

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

Since the : and the - are unique you could use:

string input;
string output;
input = "super example of string key : text I want to keep - end of my string";
output = input.Split(new char[] { ':', '-' })[1];

var matches = Regex.Matches(input, @"(?<=key :)(.+?)(?=-)");

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


I used the code snippet from Vijay Singh Rana which basically does the job. But it causes problems if the firstString does already contain the lastString. What I wanted was extracting a access_token from a JSON Response (no JSON Parser loaded). My firstString was \"access_token\": \" and my lastString was \". I ended up with a little modification

string Between(string str, string firstString, string lastString)
{    
    int pos1 = str.IndexOf(firstString) + firstString.Length;
    int pos2 = str.Substring(pos1).IndexOf(lastString);
    return str.Substring(pos1, pos2);
}

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 : ", " - ");

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

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.


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.


With dotnetcore 3.0, you can

var s = "header-THE_TARGET_STRING.7z";
var from = s.IndexOf("-") + "-".Length;
var to = s.IndexOf(".7z");
var versionString = f[from..to];  // THE_TARGET_STRING

참고URL : https://stackoverflow.com/questions/17252615/get-string-between-two-strings-in-a-string

반응형