0%

Regular Expression Notes

Regular Expression Notes

Compiler Ch03: Scanner 之 Notes

Good Online Testing

http://regexr.com/
https://regex101.com/

Rules

  • Σ 用來表示 vocabulary
  • λ 用來表示 empty string
  • characters 透過catenation(鍵接 EX:AB) 變成 string
  • Meta-characters(six): Regular Expression 的 Operator
    • ( 左括號
    • ) 右括號
    • ' 單引號
    • * 星號代表>=0, Kleene closure(A*), 可能為空
      • P* = (P+|λ)
      • P+ = PP*
    • + 加號代表>=1, 非空
    • | 一槓代表OR, Alternation(A|B)
      • a|b = [ab]
  • 0 代表空集合
  • s 代表a set of the single symbol s屬於Σ
  • - 代表single character
  • [abc] = a|b|c中括號表示包含a或b或c, “a123”, “cb12”
  • ^ 是開頭字元, 代表前面沒有任何character
    • Not(A) = (Σ-A)
    • EX: [^abc] 非a非b非c開頭
  • \d 代表digital [0-9]
  • . 任意character
  • A^k^, A^3^=AAA
  • b? = b | λ
  • {} 大括號表示他可以出現幾次

三大operations

  • Catenation(AB)
    • G -> AB
  • Alternation(A|B)
    • G -> A
    • G -> B
  • Kleene closure(A*)
    • G -> AG
    • G -> λ

Examples

1
2
3
4
5
# Int Declaration
int abc;
int abc = 123;
^(\s*int)\s+[a-zA-Z_]([a-zA-Z_]|[0-9])*\s*(=\s*[\+\-]?(0|[1-9][0-9]*))?;\s*$
1
2
3
4
5
# Float Declaration
float abc;
float abc = 0.123;
^(\s*float)\s+[a-zA-Z_]([a-zA-Z_]|[0-9])*\s*(=\s*[\-\+]?(0|0\.[0-9]+|[1-9][0-9]*\.?[0-9]+))?;\s*$

懶人包

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
[abc] 一個集合包含a,b,c (any of a, b, or c)
[^abc] 不是a|b|c的字 (not a, b, or c)
^[abc] 以a|b|c開頭
[abc]$ 以a|b|c結尾
. 任何字母(換行除外)
+ 出現1次以上
* 出現0次以上
? 出現0次或1次
[0-9]+ 數字字串
[a-zA-Z]+ 英文字串
(abc) 可視為一體
# 縮寫
\d = [0-9]
\D = !\d = [^0-9]
\w = [a-zA-Z0-9_]
\W = !\w = [^a-zA-Z0-9_]
\n = New Line (ASCII=0x0a)
\t = Tab
\r = New Line \r\n in Window (ASCII=0x0c)
\s = [\r\n\t\f\v ]
# 當?出現在*, +, {m,n}之後時,為非貪心模式:選一個操作盡可能比對最短的