How to split a string into numbers and substrings?

How to split a string into numbers and substrings?

Input: 34AG34A
Expected Result:{"34","AG","34","A"}

I tried with a function Regex.Split(), but I can't figure out which template will work.

Any ideas?

+3
source share
4 answers

A regular expression (\d+|[A-Za-z]+)will return the groups you need.

+8
source

I think you need to look for two patterns:

  • sequence of numbers
  • letter sequence

Therefore, I would use ([a-z]+)|([0-9]+).

For example, System.Text.RegularExpressions.Regex.Matches("asdf1234be56qq78", "([a-z]+)|([0-9]+)")returns 6 groups containing "asdf", "1234", "be", "56", "qq", "78".

+4
source

"", , .

" 0-9", [0-9]. \d, 0-9 .

\ d . \p {Nd}, 0-9, .

, , , , , 五 ..

. , , , . , Matches Split:

string[] output = Regex.Matches(s, "[0-9]+|[^0-9]+")
    .Cast<Match>()
    .Select(match => match.Value)
    .ToArray();
+2

Regex.Split, Regex.Match:

var m = Regex.Match("34AG34A", "([0-9]+|[A-Z]+)");
while (m.Success) {
    Console.WriteLine(m);
    m = m.NextMatch();
}

.: -)

+1

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


All Articles