Match all digits but separated by single characters

This is my line:

Hello world, '4567' is my number.

If .NET was supported /g(global modifier), there was no problem to get what I want, but now I don’t know what to do and you need your help. I need to combine all the digits ( 4567), but divided into separate characters. I want like this:

corresponds to 1: 4, match 2: 5, match 3: 6, match 4: 7

Thanks Reza

+4
source share
3 answers

You can use Regex.Matches to get all matches, i.e. numbers in your case.

var matches = Regex.Matches("Hello world, '4567' is my number.", "\\d"); 
    foreach(Match match in matches)
       Console.WriteLine(match.Value);
+6
source

Without separation:

var matches = Regex.Matches("Hello world, '4567' is my number 679.", "\\d");
for (int i = 0; i < matches.Count; i++)
    Console.WriteLine(string.Format("Match {0}: {1}", i + 1, matches[i].ToString()));

, .

:

1: 4

2: 5

3: 6

4: 7

5: 6

6: 7

7: 9

, :

var matches = Regex.Matches(myString, "\\d");
string result = string.Empty;
for (int i = 0; i < matches.Count; i++)
    result += string.Format("Match {0}: {1}", i + 1, matches[i].ToString() + ", ");

Console.WriteLine(result.Trim().Trim(','));

:

1: 4, 2: 5, 3: 6, 4: 7, 5: 6, 6: 7, 7: 9

+2

I know the question was tagged by Regex, but here is another option without REGEX

foreach (var item in "Hello world, '4567' is my number.".Where(char.IsDigit))
{
    Console.WriteLine(item);
}
+1
source

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


All Articles