我正在嘗試根據特定模式在 C# 中提取字串的一部分。
例子 :
pattern1 => string1_string2_ {0} _string3_string4.txt 應該回傳字串值“{0}”
toto_tata_2021_titi_tutu.txt should return 2021
pattern2 => string1_string2_string3_ {0} _string4.csv 應該回傳字串值“{0}”
toto_tata_titi_2022_tutu.csv should return 2022
謝謝!
uj5u.com熱心網友回復:
使用庫System.Text.RegularExpressions:
public static string ExtractYear(string s)
{
var match = Regex.Match(s, "([0-9]{8}"
"|[0-9]{4}-[0-9]{2}-[0-9]{2}"
"|[0-9]{4})");
if (match.Success)
{
return match.Groups[1].Value;
}
throw new ArgumentOutOfRangeException();
}
我為新案例添加了解決方案。您可以通過附加“|”來添加更多模式。
注意你的模式的順序。第一個首先匹配字串中的每個字符。
對于像這樣的情況,正則運算式聽起來是一個很好的選擇。
uj5u.com熱心網友回復:
string pattern = "string1_string2_{0}_string3_string4.txt";
int indexOfPlaceholder = pattern.IndexOf("{0}");
int numberOfPreviousUnderscores = pattern.Substring(0, indexOfPlaceholder).Split('_', StringSplitOptions.RemoveEmptyEntries).Length;
string stringToBeMatched = "toto_tata_2021_titi_tutu.txt";
string stringAtPlaceholder = stringToBeMatched.Split('_')[numberOfPreviousUnderscores];
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/381638.html
上一篇:Python:不能用'str'型別的非整數乘以序列::從輸入資料中分離數字中的字符
下一篇:從資料框中的字串中提取浮點值
