我從一個埠一一接收線路如下:
"value: 100.00 % "
"value: 100.00 % "
" value: 01.12 % "
等。
現在在我的 C# 代碼中,我需要將十進制數提取為 AA.BB。但是正如您所看到的,帶有百分比符號 AA.BB % 的數字可以出現在任何地方。
使用或不使用正則運算式如何做到這一點?
uj5u.com熱心網友回復:
關于您希望它如何表現,有未指定的細節。這是一種方法:
public static class InputLineParser
{
public static decimal? ExtractValue(string input)
{
var segments = input.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries);
if (segments.Length < 2) return default;
if (decimal.TryParse(segments[1], out decimal result))
{
return result;
}
return default;
}
}
這假設您的輸入具有一定的一致性。如果有兩個由空格分隔的值(不包括前導和尾隨),則第二個值被決議為小數。如果沒有兩個值或第二個值無法決議,則回傳 null。您可以選擇添加一個條件,即第一個“值”必須是文字字串“值:”。
這是單元測驗有用的地方。撰寫一些接受一些輸入并斷言回傳預期值的測驗很容易。因此,如果您想要不同的行為,但仍希望確保它在每種情況下都能按預期作業,只需添加或修改測驗資料。
[TestClass]
public class InputLineParserTests
{
[DataTestMethod]
[DataRow("value: 100.00 % ", 100)]
[DataRow("value: 100.00 % ", 100)]
[DataRow(" value: 01.12 % ", 1.12)]
public void ExtractValue_Returns_Expected_Value(string input, double expected)
{
decimal? actual = InputLineParser.ExtractValue(input);
Assert.IsTrue(actual.HasValue);
// The conversion from double to decimal is because the test
// runner didn't like doing the conversion implicitly and
// an attribute can't specify that the value is a decimal.
Assert.AreEqual((decimal)expected, actual.Value);
}
[DataTestMethod]
[DataRow("value: ")]
[DataRow("value: abc ")]
[DataRow(" ")]
public void ExtractValue_Returns_Null_When_No_Value_Found(string input)
{
decimal? actual = InputLineParser.ExtractValue(input);
Assert.IsFalse(actual.HasValue);
}
}
uj5u.com熱心網友回復:
我會使用正則運算式來解決這個問題(正則運算式 c# 檔案:https : //www.c-sharpcorner.com/article/c-sharp-regex-examples/)
//some example string
string text = "My text has 25% chance of being right, and 75 % chance of being wrong! That's not great 7";
Console.WriteLine(text); // show text to console
// Create a pattern for number([0-9] ) and maybe space([ ]*) and '%' char or nothing ([%]|)
string pattern = @"\b[0-9] [ ]*([%]|)";
// Create a Regex with this pattern
Regex rg = new Regex(pattern);
// match the pattern (form an array of all found expressions)
MatchCollection matchedNumbers = rg.Matches(text);
// for each found member print it out
for (int count = 0; count < matchedNumbers.Count; count )
Console.WriteLine(matchedNumbers[count].Value);
注意:它們將是字串而不是數字。
列印應該是:
25%
75%
7
請注意,這不會捕獲帶小數點的數字,為此您必須將其設定為更復雜的模式,如下所示: string complex_pattern = @"\b[0-9] (([.][0-9] )|)[ ]*([%]|)";
uj5u.com熱心網友回復:
嘗試這個
var numberValue = new string( value.Where(ch=> (Char.IsDigit(ch) || ch=='.')).ToArray());
輸出
100.00
100.00
01.12
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/337290.html
標籤:C#
上一篇:DataTemplateOnSelectTemplate不作業Xamarin.Forms
下一篇:我如何衡量點擊之間的時間?
