RegExp - Metacharacter Symbols

! Content: Metacharacters Symbols

Metacharacters Symbols

^ => Caret means must start with
$ => Must ends with, could matched with a word
^$ => Must begin and end with
. => Matches any ONE character
* => Matches any character 0 or more times
? => Optionals Charater
\ => Escape character


小試身手區區區

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
26
27
28
let re;
// Literal Characters
re = /hello/i

// Metacharacters Symbols
re = /^h/i; // 一定要以一個h字母開頭(in
re = /d$/i; // 一定要以一個d字母結尾(in insensitive)
re = /^hello$/i // 只有hello才符合, hello開頭, hello結尾
re = /h.llo$/i // h 和llo組合,之間需有一個字
re = /h*llo$/i // 只要是h 和llo組合,不論之間有多少文字(0或1以上)
re = /gre?a?y/i // gray和grey都符合
re = /gre?a?y\?/i // 加了escapse 符號,?就會被當作一般?, 而非options character

// String to match
const str = 'h1llo';
const result = re.exec(str)
console.log(result)

// Log Results
function reTest(re, str) {
if(re.test(str)) {
console.log(`${str} matches ${re.source}`)
} else {
console.log(`${str} does not matched ${re.source}`)
}
}

reTest(re, str)