-1

So I got piece of code, which works like if someone writes in chat !buy 3, then Regex gets that number 3 and does stuff, but how could I make code that if someone just types !buy, then it tells "him" something, else than throwing error to console because there were no number.

var getinfo = message.ToString();
Regex getInfo = new Regex("[0-9]+");
var random3 = getInfo.Match(getinfo).Value;
  • 2
    Could we see your regex, and the code that does this, to at least provide comment on? – Katana314 Mar 21 '16 at 20:30
  • Is there even a reason to use regex? If your command always comes first and the command doesn't have space(!Buy, !Sell, !View_Bag or !ViewBag) you could simple split it by space and read the first entry/check how many non-empty entries you have for providing an reply for empty commands. – Prix Mar 21 '16 at 20:33
  • I've edited first post – James Praham Mar 21 '16 at 20:35

1 Answers1

1

try this:

string getinfo = message.ToString();
Regex regex = new Regex("[0-9]+");
Match match = regex.Match(getinfo);
//if regex doesn't match
if (!match.Success)
{
    //do something.
}
SᴇM
  • 7,024
  • 3
  • 24
  • 41
  • What's that `@` in the beginning of your pattern? – Shafizadeh Mar 21 '16 at 20:36
  • @Shafizadeh [What's the @ in front of a string in C#?](http://stackoverflow.com/questions/556133/whats-the-in-front-of-a-string-in-c) – Prix Mar 21 '16 at 20:36
  • Hmm, you're code would be great, but throws me that error actually: ERROR: System.InvalidCastException: Unable to cast object of type 'System.Text.RegularExpressions.Match' to type 'System.IConvertible'. – James Praham Mar 21 '16 at 20:38
  • I've updated my answer for your example. – SᴇM Mar 21 '16 at 20:40