如何在C#中提取FontAwesome所有带前缀的完整图标类名
C# 提取FontAwesome完整带前缀图标类名方案
核心思路
FontAwesome的all.css中图标样式的选择器统一为 .{变体前缀}.{图标类名}::before 格式,例如 .fas.fa-abacus::before,因此只需要调整正则同时捕获前缀和图标类名两部分,拼接即可得到所需的完整类名。
具体实现代码
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.RegularExpressions; public class FaIconExtractor { public static List<string> GetAllFontAwesomeIcons(string cssFilePath) { var cssContent = File.ReadAllText(cssFilePath); // 正则同时匹配变体前缀(fas/far/fal/fad/fab等)和图标名 var matchResult = Regex.Matches(cssContent, @"\.(fa[rsldb])\.(fa-[a-z0-9\-]+):", RegexOptions.Multiline); // 用HashSet去重,避免重复条目 var iconSet = new HashSet<string>(); foreach (Match item in matchResult) { if (item.Success) { string fullClassName = $"{item.Groups[1].Value} {item.Groups[2].Value}"; iconSet.Add(fullClassName); } } return iconSet.ToList(); } // 调用示例 public static void Main() { var iconList = GetAllFontAwesomeIcons(@"fontawesome\all.css"); // 如需数组格式直接调用 iconList.ToArray() foreach (var icon in iconList.Take(10)) { Console.WriteLine(icon); } } }
适配说明
- 如果你使用的FontAwesome版本包含其他特殊前缀,可修改正则中
fa[rsldb]的匹配规则,将新增前缀的特征字母加入中括号即可 - 若不需要去重,可直接替换
HashSet为List,直接调用Add方法添加结果即可
内容的提问来源于stack exchange,提问作者monika-115
相关产品推荐
相关产品推荐

