我试图在 C# 中检查的内容是:
如果name_Ford_value_Focus(好)
或
name_value_Focus(不好)
符合模板
“名称_{0}_值{1}”
我必须使用正则表达式吗?
最佳答案
假设您想要匹配完整的字符串(如果不是,则从模式中删除 ^ 和 $ 以在字符串内匹配)...
class Program
{
static void Main()
{
string pattern = @"^name_.+_value_.+$";
Console.WriteLine( Regex.Match( "name_Ford_value_Focus", pattern ).Success.ToString() );//true
Console.WriteLine( Regex.Match( "name_value_Focus", pattern ).Success.ToString() );//false
//Other examples:
Console.WriteLine( Regex.Match( "name_Toyota_value_Corolla", pattern ).Success.ToString() );//true
Console.WriteLine( Regex.Match( "name_Mini_value_", pattern ).Success.ToString() );//false
Console.WriteLine( Regex.Match( "Applename_Ford_value_FocusApple", pattern ).Success.ToString() );//false because full string match. Remove ^ and $ from pattern for true
}
}
哪里:
- ^ 表示“开始于”。 $ 表示“以……结尾”。它们一起意味着匹配完整的字符串。
- 。表示匹配一个字符。
- + 表示 1 个或多个字符。
关于c# - 检查字符串是否已使用特定模板进行格式化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18736811/