[英]How to get a string between 2 specific characters in C#
正則表達式很難。
我有這個字符串:
我需要用另一個數字替換整個數字“ 11.000000”。
我如何通過說出此字符串來識別:
在“%”之前給我字符串,直到到達第一個空格(“”)為止?
嘗試這個:
string pattern = @"^Fixed Breakeven with (\d+(\.\d+)?)% Fees$";
string input = "Fixed Breakeven with 11.0000000% Fees";
var match = Regex.Match(input, pattern);
string output = string.Empty;
if (match != null)
{
output = match.Groups[1].Value;
}
您可以使用LINQ:
var myString = "Fixed Breakeven with 11.0000000% Fees";
var number = myString.Split('%').First().Split(' ').Last();
您也可以使用正則表達式進行嘗試。 這是從字符串中獲取小數的通用方法。 它適用於所有情況。
public static bool ExtractDecimalFromString(string inputString, out Decimal decimalValue)
{
Regex regex = new Regex(@"^\D*?((-?(\d+(\.\d+)?))|(-?\.\d+)).*");
Match match = regex.Match(inputString);
decimalValue = match.Success ? Convert.ToDecimal(match.Groups[1].Value) : 0;
return match.Success;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.