diff --git a/UnitsNet.Tests/QuantityParserTests.cs b/UnitsNet.Tests/QuantityParserTests.cs index 79f9a7bd72..63828fb7a5 100644 --- a/UnitsNet.Tests/QuantityParserTests.cs +++ b/UnitsNet.Tests/QuantityParserTests.cs @@ -8,6 +8,53 @@ namespace UnitsNet.Tests { public class QuantityParserTests { + [Fact] + public void Parse_WithSingleCaseInsensitiveMatch_ParsesWithMatchedUnit() + { + var unitAbbreviationsCache = new UnitAbbreviationsCache(); + unitAbbreviationsCache.MapUnitToAbbreviation(HowMuchUnit.Some, "foo"); + var quantityParser = new QuantityParser(unitAbbreviationsCache); + + HowMuch q = quantityParser.Parse("1 FOO", + null, + (value, unit) => new HowMuch((double) value, unit)); + + Assert.Equal(HowMuchUnit.Some, q.Unit); + Assert.Equal(1, q.Value); + } + + [Fact] + public void Parse_WithOneCaseInsensitiveMatchAndOneExactMatch_ParsesWithTheExactMatchUnit() + { + var unitAbbreviationsCache = new UnitAbbreviationsCache(); + unitAbbreviationsCache.MapUnitToAbbreviation(HowMuchUnit.Some, "foo"); + unitAbbreviationsCache.MapUnitToAbbreviation(HowMuchUnit.ATon, "FOO"); + var quantityParser = new QuantityParser(unitAbbreviationsCache); + + HowMuch q = quantityParser.Parse("1 FOO", + null, + (value, unit) => new HowMuch((double) value, unit)); + + Assert.Equal(HowMuchUnit.ATon, q.Unit); + Assert.Equal(1, q.Value); + } + + [Fact] + public void Parse_WithMultipleCaseInsensitiveMatchesButNoExactMatches_ThrowsUnitNotFoundException() + { + var unitAbbreviationsCache = new UnitAbbreviationsCache(); + unitAbbreviationsCache.MapUnitToAbbreviation(HowMuchUnit.Some, "foo"); + unitAbbreviationsCache.MapUnitToAbbreviation(HowMuchUnit.ATon, "FOO"); + var quantityParser = new QuantityParser(unitAbbreviationsCache); + + void Act() + { + quantityParser.Parse("1 Foo", null, (value, unit) => new HowMuch((double) value, unit)); + } + + Assert.Throws(Act); + } + [Fact] public void Parse_MappedCustomUnit() { diff --git a/UnitsNet/CustomCode/QuantityParser.cs b/UnitsNet/CustomCode/QuantityParser.cs index 0f4a4028e4..afe9db276f 100644 --- a/UnitsNet/CustomCode/QuantityParser.cs +++ b/UnitsNet/CustomCode/QuantityParser.cs @@ -222,7 +222,7 @@ private string CreateRegexPatternForQuantity(IFormatProvider formatPr private Regex CreateRegexForQuantity([CanBeNull] IFormatProvider formatProvider) where TUnitType : Enum { var pattern = CreateRegexPatternForQuantity(formatProvider); - return new Regex(pattern, RegexOptions.Singleline); + return new Regex(pattern, RegexOptions.Singleline | RegexOptions.IgnoreCase); } } }