기본 사용법

1
2
3
4
5
6
7
const name = "My name is Kim";
const pattern = /Kim/;

pattern.test(name); // true
pattern.exec(name); // ["Kim"]

name.match(pattern); // ["Kim"]

반복

?

1개 or 0개

1
2
3
4
5
6
const name = "Kim YongHoon Kim";
const name2 = "Kim YongHoon";
const pattern = /Kim?/;

pattern.test(name); // true
pattern.test(name2); // true

+

1개 이상

1
2
3
4
5
const text = "catz";
const text2 = "catcatz";
const pattern = /cat+w/;
pattern.test(text); // true
pattern.test(text2); // true

*

0개 이상

1
2
3
4
5
6
const text = "catz";
const pattern = /cab*tz/;
//만약 *를 문자로써 취급하고 싶다면 \*로 사용

pattern.test(text); // true
pattern.exec(text); // ["catz"]

길이 지정

{n} : n번 연속
{n,} : 최소 n번 연속
{m, n} : 최소 m번, 최대 n번

1
2
3
4
const text = "appppppppppppppppple";
text.match(/ap{4}/); // ["apppp"]
text.match(/ma{4,}/); // ["appppppppppppppppp"]
text.match(/ma{4,6}/); // ["apppppp"]

[]

범위 지정 + 편의성

1
2
3
4
5
6
7
const text ='YongHoon';
text.match(/[abcdefghifklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ]\*/);
// ["YongHoon"]

const text ='YongHoon94';
const.match(/[a-zA-Z0-9]\*/);
// ["YongHoon94"]