How to split a string without delimiters and if possible with regex

Hi,

How do i split a string based on length without delimiters

Eg. “ABCDEFGH”

Now the length of the string is 8, what I want is to split the string as “AB C DE F GH” if the length of the string is even and as “ABC D E F G H” if the length of the string is odd.

Any help please.

Hi,

How about the following?

Even

arrResult = System.Text.RegularExpressions.Regex.Matches(yourString,"^..|..$|(?<=..+?).(?=..+$)").Cast(Of System.Text.RegularExpressions.Match).Select(Function(m) m.Value).ToArray

Odd

arrResult = System.Text.RegularExpressions.Regex.Matches(yourString,"^...|(?<=...+?).").Cast(Of System.Text.RegularExpressions.Match).Select(Function(m) m.Value).ToArray

Sample20221202-1.zip (2.5 KB)

Regards,

Hi,

Thanks for the reply, it works if the length is odd but if the length of the string is even the output is not as expected.

Hi,

Can you share some specific input and expected output?

Regards,

Hi,

Input: “ABCDEF”

Now the length of the string is 6 and even so,

Expected Output: “AB C DE F”

Thanks

Hi,

What about 10 length such as “ABCDEFGHIJ”?

Is this “AB C DE F GH I J” ?

Regards,

Hi,

Yes, if this is not possible with regex then using split is also fine

Thanks

Hi,

Can you try the following expression?

arrResult = Enumerable.Range(0,yourString.Length).Where(Function(i) i mod 3<>1).Select(Function(i,idx) String.Join("",yourString.Skip(i).Take(2-(idx mod 2)))).ToArray

Sample20221202-1v2.zip (2.7 KB)

Regards,

Thanks working as expected

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.