MitchellJ
MitchellJ

Reputation: 13

How do I Extract negative and positive int from a string in C#

The code will display ten when I need it to display the error message

int _userInt = 0;
string _checkForNumbers = "Mitchell, -10";
var _intInput = string.Join("", _checkForNumbers.Where(char.IsDigit));
int.TryParse(_intInput, out _userInt);
if(_userInt < 0)
{
  Console.WriteLine("Please only enter positive numbers");
  Console.ReadKey(true);
}
else
{
  Console.Write($"{_userInt}");
  Console.ReadKey(true);
}

Upvotes: 1

Views: 3267

Answers (4)

slnit
slnit

Reputation: 35

public void TryThis()

    {
        string pattern = @"\-*\d+";
        string value="Mitchell, -10";
        Match oMatch=Regex.Match(value,pattern);

        if (int.Parse(oMatch.Value) < 0)
        {
            Console.WriteLine(oMatch.Value);
            Console.ReadKey(true);
        }
        else
        {
            Console.WriteLine(oMatch.Value);
            Console.ReadKey(true);
        }
    }

Upvotes: 0

tu4n
tu4n

Reputation: 4450

using System.Text.RegularExpressions;

     string src = "Mitchell, 4-10-5arbitrary-text3";
     var matches = Regex.Matches(src, @"-?\d+");
     matches[0].Value; //4
     matches[1].Value; //-10;
     matches[2].Value; //-5
     matches[3].Value; //3

Those Value are string, you need to call int.Parse to get integer value

MSDN
TutorialsPoint

Upvotes: 0

haydnD
haydnD

Reputation: 2293

Try extracting numbers with regex

public static decimal[] intRemover (string input)
{
    int n=0;
    MatchCollection matches=Regex.Matches(input,@"[+-]?\d+(\.\d+)?");
    decimal[] decimalarray = new decimal[matches.Count];

    foreach (Match m in matches) 
    {
            decimalarray[n] = decimal.Parse (m.Value);
            n++;
    }
    return decimalarray;
}

Number extraction from strings using Regex

Upvotes: 4

Eser
Eser

Reputation: 12546

I think This simple linq should work,

int temp = 0;
var strInt = checkForNumbers.Split().First(x => int.TryParse(x, out temp));

Upvotes: 2

Related Questions