利用ASP.NET的Regex取出.css檔裡的樣式名稱
最近同事在問有沒有可以讀取css檔的.net framework 2.0的類別可以用....
我也不知道有沒有..但有找到一些open source的API可以用,是java的
也找到了一個用正規表達式的方法...取出css檔裡的所有樣式名稱..分享給大家呀..
c#範例:
01
using System;
02
using System.Data;
03
using System.Configuration;
04
using System.Collections;
05
using System.Web;
06
using System.Web.Security;
07
using System.Web.UI;
08
using System.Web.UI.WebControls;
09
using System.Web.UI.WebControls.WebParts;
10
using System.Web.UI.HtmlControls;
11
using System.Text.RegularExpressions;
12
13
public partial class CSSRegex : System.Web.UI.Page
14
{
15
protected void Page_Load(object sender, EventArgs e)
16
{
17
//假設下面是css檔的內容
18
string css = @"
19
20 .text
21
{ /*font-size: 1em;*/
22
color: #0099CC;
23
font-weight: bold;
24
text-decoration: none;
25
list-style-type: decimal;
26
line-height: 1.8em;
27
}
28
29
.h0 {
30
font-size: 1em;
31
color: #009966;
32
text-decoration: none;
33
font-weight: bold;
34
}
35
.h1 {
36
font-size: 1em;
37
color: #669900;
38
text-decoration: none;
39
font-weight: bold;
40
}
41
.h2 {
42
font-size: 1em;
43
color: #FF9933;
44
text-decoration: none;
45
font-weight: bold;
46
}
47
48 ";
49
50 //這行是取出CSS樣式名稱的正規表達式
51
MatchCollection arr = Regex.Matches(css, @"(?<!url\s*\(.*)(\.[-]?[_a-zA-Z][_a-zA-Z0-9-]*|[^\0-\177]*\\[0-9a-f]{1,6}(\r\n[ \n\r\t\f])?|\\[^\n\r\f0-9a-f]*)");
52
53 foreach (Match str in arr)
54
{
55
Response.Write(str.Value + "<br/>");
56
}
57
58
}
59
}
60

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20 .text
21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48 ";
49

50 //這行是取出CSS樣式名稱的正規表達式
51

52

53 foreach (Match str in arr)
54

55

56

57

58

59

60
執行結果: