[英]How to Get string value between a string value
“該示例適用於 C# - 值是 -Here is value。” 我想從我嘗試過的這個字符串值中獲取值(這里是值),但是當字符串值中有兩個 (-) 破折號並且無法獲取值時,它會給我錯誤。 我怎么能做到這一點,我已經嘗試過。
String St = "The example is for C# - The value is -Default ID.";
int pFrom = St.IndexOf(" - ") + "- ".Length;
int pTo = St.LastIndexOf(" . ");
String result = St.Substring(pFrom, pTo - pFrom);
當 sentence 中只有 one(-) 時它工作正常。 如何從字符串中獲取值(默認 ID)。
您可以使用正則表達式模式[^-]*$
例子
var input = "The example is for C# - The value is -Default ID.";
var match = Regex.Match(input, @"[^-]*$");
if (match.Success)
Console.WriteLine(match.Value);
輸出
Default ID.
解釋
可視化
不需要兩個索引,只需使用最后一次出現的“-”。
嘗試:
String St = "The example is for C# - The value is -Default ID.";
String result = St.Substring(s.LastIndexOf("-") + 1);
如果要在末尾刪除句點,可以執行以下操作:
String finalResult = result.Remove(result.Length - 1, 1);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.