Reputation: 1644
This is my string:
Hello world, '4567' is my number.
If /g
(global modifier) was supported in .NET, There was no problem to get what I want, but now, I don't know what to do and need your help. I need match all digits (4567
) but splitted in single characters. I want it like this:
match 1: 4, match 2: 5, match 3: 6, match 4: 7
Thanks, Alireza
Upvotes: 4
Views: 79
Reputation: 223287
I know the question has been tagged with Regex, but here is another option without REGEX
foreach (var item in "Hello world, '4567' is my number.".Where(char.IsDigit))
{
Console.WriteLine(item);
}
Upvotes: 1
Reputation: 1206
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()));
It also works if you have more than once numbers in your string.
Output:
Match 1: 4
Match 2: 5
Match 3: 6
Match 4: 7
Match 5: 6
Match 6: 7
Match 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(','));
Output:
Match 1: 4, Match 2: 5, Match 3: 6, Match 4: 7, Match 5: 6, Match 6: 7, Match 7: 9
Upvotes: 2
Reputation: 148140
You can use Regex.Matches to get all the matches i.e. digits in your case.
var matches = Regex.Matches("Hello world, '4567' is my number.", "\\d");
foreach(Match match in matches)
Console.WriteLine(match.Value);
Upvotes: 6