Turn a line such as sell 12.5 kg wool @ 4.20 into a trade without scattering string splits through your game loop. This console trading post extracts named fields, converts the numbers, then checks the purse and inventory before changing either balance.
The complete program below targets .NET 10 and uses only the base class library. Its default mode replays fifteen commands and asserts the result. Pass --play to enter trades through Console.ReadLine.
Set the market rules first
You start with 100 coins and an empty inventory. The market has unlimited supply and buys back goods at their catalog price unless you specify another price.
| Item | Unit | Coins per unit |
|---|---|---|
| salt | piece | 2 |
| wool | kg | 4 |
| tea | kg | 6 |
| grain | kg | 1 |
| lamp | piece | 10 |
The grammar is deliberately small: lowercase buy or sell, a quantity, an optional unit, an item, and an optional @ unit price. Use ordinary spaces between fields, a dot for decimals, and at most two fractional digits. Leading or trailing spaces, signs, commas, tabs and extra words are rejected. Omitting the unit selects the item’s catalog unit; omitting the price selects its catalog price.
buy 3 salt
buy 12.5 kg wool @ 4.20
sell 2 kg wool @ 5.00
A supplied price is accepted as a game choice: you can buy low and sell high immediately. There is no negotiation, price discovery, market inventory or win condition here. The lesson is command parsing and consistent state changes.
Extract fields, then decide whether a trade is legal
There is one cached Regex for each verb, both using RegexOptions.Compiled and the same tail pattern. The five named captures are verb, qty, unit, item and price. Microsoft’s grouping guide documents named captures and accessing their values through Match.Groups. Optional groups let the game distinguish an omitted field from a supplied value.
The pattern uses \A and \z to require the entire input. Its noncapturing groups organize optional syntax without creating additional fields. Each regex has a 250 ms match timeout; the handler catches RegexMatchTimeoutException. The Regex constructor reference documents the options and timeout overload. Input is also limited to 160 characters. These are bounds for this exercise, not a performance benchmark.
After matching, decimal.TryParse receives NumberStyles.AllowDecimalPoint and CultureInfo.InvariantCulture. The regex restricts the spelling; the parser checks whether the numeric value is representable. Supplying a provider avoids relying on the machine’s current culture. Microsoft’s numeric parsing guide explains format providers, styles and the false result from failed TryParse calls. For a broader comparison, see NumberStyles and culture in C#.
The result has three categories. A malformed command fails the grammar, exceeds the length limit, times out or fails numeric conversion. A rule rejection names an unavailable item, uses the wrong unit, requests fractional pieces, exceeds a bound or lacks coins or stock. An accepted command changes both balances. The code checks the item before converting an optional price, so an unknown item takes precedence if both fields are wrong.
Quantities and unit prices must each be greater than zero and at most 1000. The purse and each inventory balance are capped at one million. These bounds keep the arithmetic comfortably within decimal‘s range. Totals keep decimal precision without rounding to whole cents: quantities and prices with two fractional digits can produce four fractional digits in a total. The state display shows coins to two decimal places, while the stored balance retains the full value.
Run the complete program
Create a console project using the .NET 10 SDK, then replace its entire Program.cs with the following program. No packages are needed.
dotnet new console --framework net10.0 --name TradingPost
cd TradingPost
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text.RegularExpressions;
if (args.Length == 1 && args[0] == "--play")
{
var game = new TradingPost();
Console.WriteLine("Trading post: buy/sell QTY [kg|piece] ITEM [@ PRICE]");
Console.WriteLine("Goods: salt 2/piece, wool 4/kg, tea 6/kg, grain 1/kg, lamp 10/piece.");
Console.WriteLine("Use lowercase, dot decimals, and at most two decimal places. EOF exits.");
Console.WriteLine(game.State());
string? line;
while ((line = Console.ReadLine()) is not null)
{
Outcome outcome = game.Execute(line);
Console.WriteLine($"{outcome.Kind}: {outcome.Message}");
Console.WriteLine(game.State());
}
}
else
{
// Run the same script under two current cultures; parsing must stay identical.
CultureInfo original = CultureInfo.CurrentCulture;
try
{
foreach (string culture in new[] { "en-US", "fr-FR" })
{
CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo(culture);
var game = new TradingPost();
string[] script =
{
"buy 3 salt", "buy 12.5 kg wool @ 4.20",
"sell 2 kg wool @ 5.00", "buy 2 tea", "sell 1 salt",
"buy 4 grain", "sell 0.5 kg tea @ 8", "buy 1 lamp",
"sell 1 lamp @ 12", "sell 2 grain @ 1.50",
"buy -1 salt", "buy 1,5 wool", "sell salt",
"buy 2 salt trailing", "trade 1 tea"
};
int accepted = 0, malformed = 0, ruleRejected = 0;
for (int i = 0; i < script.Length; i++)
{
Outcome result = game.Execute(script[i]);
Check(result.Kind == (i < 10 ? "accepted" : "malformed"), "script classification");
if (result.Kind == "accepted") accepted++;
else if (result.Kind == "malformed") malformed++;
else ruleRejected++;
}
Check(accepted == 10 && malformed == 5 && ruleRejected == 0, "counts");
Check(game.Coins == 46.50m, "purse");
Check(game.Stock("salt") == 2m && game.Stock("wool") == 10.5m &&
game.Stock("tea") == 1.5m && game.Stock("grain") == 2m &&
game.Stock("lamp") == 0m, "all five inventory balances");
Console.WriteLine($"{culture}: accepted=10 malformed=5 rule-rejected=0");
Console.WriteLine(game.State());
// These probes are separate from the 15-command script.
var probe = new TradingPost();
string before = probe.State();
string[] ruleFailures =
{
"buy 1000 lamp", "sell 1 salt", "buy 1 kg salt",
"buy 0 salt", "buy 0.5 salt", "buy 1 unknown",
"buy 1 salt @ 0", "buy 1001 grain"
};
foreach (string command in ruleFailures)
{
Check(probe.Execute(command).Kind == "rule-rejected", command);
Check(probe.State() == before, "rejection must preserve state");
}
Check(probe.Execute("buy 999999999999999999999999999999999 salt").Kind ==
"malformed", "numeric overflow");
Check(probe.Execute("buy 1.234 wool").Kind == "malformed", "precision limit");
Check(probe.State() == before, "malformed input must preserve state");
Console.WriteLine("Extra probes: 8 rule rejections and 2 malformed inputs; state unchanged.");
}
}
finally { CultureInfo.CurrentCulture = original; }
Console.WriteLine("PASS");
}
static void Check(bool condition, string label)
{
if (!condition) throw new InvalidOperationException("Assertion failed: " + label);
}
record Outcome(string Kind, string Message);
record Good(string Unit, decimal Price);
sealed class TradingPost
{
private const string Tail =
@"[ ]+(?<qty>[0-9]+(?:\.[0-9]{1,2})?)[ ]+(?:(?<unit>kg|piece)[ ]+)?" +
@"(?<item>[a-z]+)(?:[ ]+@[ ]+(?<price>[0-9]+(?:\.[0-9]{1,2})?))?\z";
private static readonly Regex Buy = Make(@"\A(?<verb>buy)" + Tail);
private static readonly Regex Sell = Make(@"\A(?<verb>sell)" + Tail);
private static Regex Make(string pattern) => new(pattern, RegexOptions.Compiled,
TimeSpan.FromMilliseconds(250));
private static readonly CultureInfo Invariant = CultureInfo.InvariantCulture;
private readonly Dictionary<string, Good> goods = new()
{
["salt"] = new("piece", 2m), ["wool"] = new("kg", 4m),
["tea"] = new("kg", 6m), ["grain"] = new("kg", 1m),
["lamp"] = new("piece", 10m)
};
private readonly Dictionary<string, decimal> inventory = new()
{
["salt"] = 0m, ["wool"] = 0m, ["tea"] = 0m,
["grain"] = 0m, ["lamp"] = 0m
};
public decimal Coins { get; private set; } = 100m;
public decimal Stock(string item) => inventory[item];
public Outcome Execute(string input)
{
if (input.Length > 160) return new("malformed", "Keep commands within 160 characters.");
Match match;
try
{
match = Buy.Match(input);
if (!match.Success) match = Sell.Match(input);
}
catch (RegexMatchTimeoutException)
{
return new("malformed", "Matching timed out; try a shorter command.");
}
if (!match.Success)
return new("malformed", "Use: buy/sell QTY [kg|piece] ITEM [@ PRICE]; example: buy 3 salt.");
if (!decimal.TryParse(match.Groups["qty"].Value, NumberStyles.AllowDecimalPoint,
Invariant, out decimal quantity))
return new("malformed", "Quantity cannot be represented as a decimal.");
string item = match.Groups["item"].Value;
if (!goods.TryGetValue(item, out Good? good))
return new("rule-rejected", "Choose salt, wool, tea, grain or lamp.");
decimal price = good.Price;
if (match.Groups["price"].Success &&
!decimal.TryParse(match.Groups["price"].Value, NumberStyles.AllowDecimalPoint,
Invariant, out price))
return new("malformed", "Price cannot be represented as a decimal.");
if (quantity <= 0m || quantity > 1000m || price <= 0m || price > 1000m)
return new("rule-rejected", "Quantity and unit price must each be greater than 0 and at most 1000.");
string unit = match.Groups["unit"].Success ? match.Groups["unit"].Value : good.Unit;
if (unit != good.Unit || (unit == "piece" && quantity != decimal.Truncate(quantity)))
return new("rule-rejected", "Use the catalog unit and whole quantities for piece goods.");
decimal total = quantity * price;
bool buying = match.Groups["verb"].Value == "buy";
decimal nextCoins = Coins + (buying ? -total : total);
decimal nextStock = inventory[item] + (buying ? quantity : -quantity);
if (nextCoins < 0m || nextStock < 0m)
return new("rule-rejected", "Not enough coins or stock.");
if (nextCoins > 1000000m || nextStock > 1000000m)
return new("rule-rejected", "Purse and each stock balance are capped at one million.");
Coins = nextCoins;
inventory[item] = nextStock;
return new("accepted", "Trade complete.");
}
public string State() =>
"Coins=" + Coins.ToString("0.00", Invariant) +
"; salt=" + Stock("salt").ToString("0.##", Invariant) +
"; wool=" + Stock("wool").ToString("0.##", Invariant) +
"; tea=" + Stock("tea").ToString("0.##", Invariant) +
"; grain=" + Stock("grain").ToString("0.##", Invariant) +
"; lamp=" + Stock("lamp").ToString("0.##", Invariant);
}
Run the assertions first, then start an interactive session:
dotnet run
dotnet run -- --play
Interactive mode starts a fresh market, prints the catalog and current state, and reports each result with an error message when needed. End input with Ctrl+D on Unix-like terminals or Ctrl+Z followed by Enter on Windows.
Check the replay and rejection boundaries
The script’s first ten commands are accepted trades; its last five are malformed. It checks each classification, the exact counts, the final purse and all five stock balances. The wool purchase costs 52.50 coins. Completing all ten trades leaves 46.50 coins, two salt, 10.5 kg of wool, 1.5 kg of tea, two kg of grain and no lamps.
Separate probes check eight rule rejections, numeric overflow and excessive fractional digits. Every rejection leaves the probe’s initial state unchanged. The whole test runs under both en-US and fr-FR current cultures, restores the original culture, and throws if an assertion fails.
This exact program compiled and ran successfully in an offline Linux .NET 10 SDK container. The observed output matched the expected output exactly:
en-US: accepted=10 malformed=5 rule-rejected=0
Coins=46.50; salt=2; wool=10.5; tea=1.5; grain=2; lamp=0
Extra probes: 8 rule rejections and 2 malformed inputs; state unchanged.
fr-FR: accepted=10 malformed=5 rule-rejected=0
Coins=46.50; salt=2; wool=10.5; tea=1.5; grain=2; lamp=0
Extra probes: 8 rule rejections and 2 malformed inputs; state unchanged.
PASS
The interactive branch shares the tested parser and trade logic; terminal input itself was not exercised by the headless fixture. To extend the game, add a fixed market price schedule or a target purse, then add commands and expected balances to the replay before changing the rules. For another bounded regex exercise, try C# regex golf; for a game built around object capabilities, see the small-interface text adventure.