enb081
enb081

Reputation: 4051

How can I get all substrings of a string that consist of a special char and a number after it - C#

I have strings in the following format:

string s1 = "#1233 + #343 - #24311";
string s2 = "(#563*#534)/#2333";

For each string, how can I get all the substrings that are of the form #NUMBER?

For instance: #1233, #343, #24311

Note that the number of digits of these numbers is not fixed, and they are not necessarily separated by spaces.

Upvotes: 0

Views: 84

Answers (1)

Ilya Ivanov
Ilya Ivanov

Reputation: 23636

As GSerg kindly noted the regular expression, I just want to show the implementation:

MatchCollection matches = Regex.Matches(s1, @"#\d+");

string[] result = matches.Cast<Match>()
                         .Select(match => match.Value)
                         .ToArray();

Console.WriteLine( string.Join(Environment.NewLine, result) );

prints for s1

#1233
#343
#24311

Upvotes: 2

Related Questions