Get line between lines in C #

I am trying to get a line between the same lines:

The texts starts here ** Get This String ** Some other text ongoing here.....

I am wondering how to get a string between stars. Should I use some regex or other functions?

+4
source share
6 answers

You can try Split:

  string source = 
    "The texts starts here** Get This String **Some other text ongoing here.....";

  // 3: we need 3 chunks and we'll take the middle (1) one  
  string result = source.Split(new string[] { "**" }, 3, StringSplitOptions.None)[1];
+4
source

You can use IndexOfto do the same without regular expressions.
This will return the first occurrence of the line between the two "**" with truncated spaces. It also has non-existence checks for a string that matches this condition.

public string FindTextBetween(string text, string left, string right)
{
    // TODO: Validate input arguments

    int beginIndex = text.IndexOf(left); // find occurence of left delimiter
    if (beginIndex == -1)
        return string.Empty; // or throw exception?

    beginIndex += left.Length;

    int endIndex = text.IndexOf(right, beginIndex); // find occurence of right delimiter
    if (endIndex == -1)
        return string.Empty; // or throw exception?

    return text.Substring(beginIndex, endIndex - beginIndex).Trim(); 
}    

string str = "The texts starts here ** Get This String ** Some other text ongoing here.....";
string result = FindTextBetween(str, "**", "**");

I usually prefer not to use regex when possible.

+3
source

, :

.*\*\*(.*)\*\*.*

.

IndexOf, , , , . Substring .

+2

, :

\*\*(.*?)\*\*

:

string data = "The texts starts here ** Get This String ** Some other text ongoing here..... ** Some more text to find** ...";
Regex regex = new Regex(@"\*\*(.*?)\*\*");
MatchCollection matches = regex.Matches(data);

foreach (Match match in matches)
{
    Console.WriteLine(match.Groups[1].Value);
}
0

SubString :

String str="The texts starts here ** Get This String ** Some other text ongoing here";

s=s.SubString(s.IndexOf("**"+2));
s=s.SubString(0,s.IndexOf("**"));
0

split, .

:

string output = "";
string input = "The texts starts here **Get This String **Some other text ongoing here..";
var splits = input.Split( new string[] { "**", "**" }, StringSplitOptions.None );
//Check if the index is available 
//if there are no '**' in the string the [1] index will fail
if ( splits.Length >= 2 )
    output = splits[1];

Console.Write( output );
Console.ReadKey();
0

Source: https://habr.com/ru/post/1674286/


All Articles