简体   繁体   中英

Split string on a Regex

I have the following strings

  1. mo474334pt1572
  2. at1088ma15
  3. ma15pt1983
  4. ca1

I want to obtain

a) string[] result = new[] {"mo474334", "pt1572"};
a) string[] result = new[] {"at1088", "ma15"};
a) string[] result = new[] {"ma15", "pt1983"};
c) string[] result = new[] {"ca1"};

I have been trying the following approaches with little success

string[] result = Regex.Split(str, @"\[A-Za-z]{2}[0-9]*");

string[] result = Regex.Split(str, @"\[A-Za-z]{2}[0-9]*\[A-Za-z]{2}[0-9]*");

and

string[] result = Regex.Matches(str, @"^[A-Za-z]{2}[0-9]*").Cast<Match>().Select(m => m.Value).ToArray();

Can anyone see where I am going wrong, Is this achieveable ? Or should I use another approach

Instead of split, you could match 2 times a char a-zA-Z and 1 or more digits 0-9

[A-Za-z]{2}[0-9]+

Regex demo | C# demo


If you want to use split, one way could be using a positive lookahead

\B(?=[A-Za-z]{2}[0-9])
  • \\B Assert a position where a wordboundary does not match
  • (?= Positive lookahead, assert what is on the right is
    • [A-Za-z]{2}[0-9] match 2 times a char a-zA-Z
  • ) Close lookahead

Regex demo | C# demo

在此处输入图片说明

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