1

I have strings like

AS_!SD 2453iur ks@d9304-52kasd

I need to get the 2 frist numbres of the string:

for that case will be: 2453 and 9304

I don't have any delimiter in the string to try a split, and the length of the numbers and string is variable, I'm working in C# framework 4.0 in a WPF.

thanks for the help, and sorry for my bad english

1
  • 1
    Use the regular expression \d{4} and take the first matches. Commented Mar 21, 2013 at 14:43

3 Answers 3

9

This solution will take two first numbers, each can have any number of digits

string s =  "AS_!SD 2453iur ks@d9304-52kasd";

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

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

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

will print

2453
9304

you can parse them to int[] by result.Select(int.Parse).ToArray();

Sign up to request clarification or add additional context in comments.

2 Comments

where i can read more about the regular expressions?, it seems to be an Amazing tool
@PachoBeltrán the one and only book on this subject is Mastering Regular Expressions by Jeffrey E.F. Friedl amzn.to/Zfy7jo
0

You can loop chars of your string parsing them, if you got a exception thats a letter if not is a number them you must to have a list to add this two numbers, and a counter to limitate this.

follow a pseudocode:

for char in string:

if counter == 2:
 stop loop

if parse gets exception
 continue

else
 loop again in samestring stating this point
 if parse gets exception
  stop loop
 else add char to list

Comments

0

Alternatively you can use the ASCII encoding:

string value = "AS_!SD 2453iur ks@d9304-52kasd";

byte zero = 48; // 0
byte nine = 57; // 9

byte[] asciiBytes = Encoding.ASCII.GetBytes(value);

byte[] asciiNumbers = asciiBytes.Where(b => b >= zero && b <= nine)
                    .ToArray();

char[] numbers = Encoding.ASCII.GetChars(asciiNumbers);

// OR

string numbersString =  Encoding.ASCII.GetString(asciiNumbers);

//First two number from char array
int aNum = Convert.ToInt32(numbers[0]);
int bNum =  Convert.ToInt32(numbers[1]);

//First two number from string
string aString = numbersString.Substring(0,2);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.