Split strings and string arrays

string s= abc**xy**efg**xy**ijk123**xy**lmxno**xy**opq**xy**rstz;

I need the output as a string array, where it is divided by "xy". I used

  string[] lines = Regex.Split(s, "xy"); 

here he deletes xy. I want an array along with xy. So, after I split the string into a string array, the array should be as follows.

lines[0]= abc;
lines[1]= xyefg;
lines[2]= xyijk123;
lines[3]= xylmxno;
lines[4]= xyopq ;
lines[5]= xyrstz;

How can i do this?

+4
source share
4 answers
(?=xy)

You need to divide by. 0 width assertionWatch the demo.

https://regex101.com/r/fM9lY3/50

string strRegex = @"(?=xy)";
Regex myRegex = new Regex(strRegex, RegexOptions.None);
string strTargetString = @"abcxyefgxyijk123xylmxnoxyopqxyrstz";

return myRegex.Split(strTargetString);

Output:

abc xyefg xyijk123 xylmxno xyopq xyrstz

+3
source

If you are not married to Regex, you can make your own extension method:

public static IEnumerable<string> Ssplit(this string InputString, string Delimiter)
{
    int idx = InputString.IndexOf(Delimiter);
    while (idx != -1)
    {
        yield return InputString.Substring(0, idx);
        InputString = InputString.Substring(idx);

        idx = InputString.IndexOf(Delimiter, Delimiter.Length);
    }

    yield return InputString;
}

Using:

string s = "abc**xy**efg**xy**ijk123**xy**lmxno**xy**opq**xy**rstz";
var x = s.Ssplit("xy");
+2
source

:

string s = "abc**xy**efg**xy**ijk123**xy**lmxno**xy**opq**xy**rstz";

string[] lines = Regex.Split(s, "xy");

lines = lines.Take(1).Concat(lines.Skip(1).Select(l => "xy" + l)).ToArray();

:

lines

, ** - . RegEx @"\*\*xy\*\*" **.

+2

How about a simple loop for an array starting at index 1 and adding the string "xy" to each record?

Alternatively, implement your own version of split, which shortens the string the way you want it.

Yeat another solution will match "xy *" in a non-greedy way, and your array will be a list of all matches. Depending on the language, this will probably not be called split BTW.

0
source

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


All Articles