[英]Parse string in C# using regex and replace
我必須將 C# 中的字符串解析為:
一些文字 [ first_name | 用戶 ] 一些其他文本。 [ 你的生日是 yy/mm/dd | ]
例子:
親愛的 [ 名字 | 用戶],你好嗎? [ 你的生日是 yy/mm/dd | ]
所以,我檢查整個文本中的括號[]
,刪除字符前后的空格: [
, |
, ]
並從數據庫中填充first_name
,如果first_name
不可用,則替換為在這種情況下為User
的替代文本。
如果數據庫中沒有生日禮物,則將Your birthday is on yy/mm/dd
替換為null
。
我知道正則表達式用於字符串匹配,但我如何進行字符串替換,例如: Replace("first_name", Name);
在正則表達式?
有第三方庫嗎?
正則表達式可以做到這一點:) 請嘗試這樣的事情:
class Program
{
static void Main(string[] args)
{
var processedText = Regex.Replace("Some text [first_name | User] some other text. [Your birthday is on yy / mm / dd | ]. " +
"Dear [ first_name | User ], How are you?. [ Your birthday is on yy/mm/dd | ]",
@"\[\s*(.*?)\s*\|\s*(.*?)\s*\]", new MatchEvaluator(ReplaceAction));
Console.WriteLine(processedText);
}
public static bool DummyTryGetValueFromDb(string key, out string value)
{
Random randomizer = new Random(DateTime.UtcNow.Millisecond);
if (randomizer.Next(100) > 50) // Successfully found in db :)
{
if (key == "first_name")
{
value = "Toto";
return true;
}
else
{
value = "Your birthday is on your birthday date from db !";
return true;
}
}
else
{
value = string.Empty;
return false;
}
}
public static string ReplaceAction(Match match)
{
if (match.Groups.Count > 1)
{
var dataKeyGroup = match.Groups[1];
if (DummyTryGetValueFromDb(dataKeyGroup.Value, out var valueFromDb))
return valueFromDb;
else if (match.Groups.Count > 2)
return match.Groups[2].Value;
else
return "[Not found from db, no alternative value]"; // you can throw exception
}
else
return "[Bad syntax]"; // you can throw exception
}
}
Regex.Replace("Dear [ first_name | User ], How are you?. [ Your birthday is on yy/mm/dd | ]", "Your Pattern", firstName ?? User)
您需要Regex.Replace
方法。 下面的示例取自教程,因此該模式可能不適合您。
string testString = "<b>Hello, <i>world</i></b>";
Regex regex = new Regex("<[^>]+>");
string cleanString = regex.Replace(testString, "");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.