简体   繁体   中英

Split string and string arrays

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

I want the output as string array, where it get splits at "xy". I used

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

here it removes xy . I want array along with xy . So, after I split my string to string array, array should be as below.

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

how can i do this?

(?=xy)

You need to split on 0 width assertion .See 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

If you're not married to Regex, you could 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;
}

Usage:

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

It seems fairly simple to do this:

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

I get the following result:

线

I don't know if you wanted to keep the ** - your question doesn't make it clear. Changing the RegEx to @"\\*\\*xy\\*\\*" will remove the ** .

How about simply looping throgh the array starting with index 1 and adding the "xy" string to each entry?

Alternatively implement your own version of split that cuts the string how you want it.

Yeat another solution would be matching "xy*" in a non-greedy way and your array would be the list of all matches. Depending on language this probably won't be called split BTW.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM