정규표현식 (RegExp)
1. 정규식의 역할
- 문자 검색(search)
- 문자 대체(replace)
- 문자 추출(extract)
2. 정규식 테스트 사이트
https://regexr.com/
3. 정규식 생성 방식
let str = `
010-1234-5678
thesecon@gmail.com
https://www.omdbapi.com/?apikey=7035c60c&s=frozen
The quick brown fox jumps over the lazy dog.
abcccdddd
`
new RegExp('표현', '옵션')
new RegExp('[a-z]', 'gi')
let regexp = new RegExp('the','')
console.log(str.match(regexp))
regexp = new RegExp('the','g')
console.log(str.match(regexp))
regexp = new RegExp('the','gi')
console.log(str.match(regexp))
/표현/옵션
/[a-z]/gi
regexp = /the/gi
console.log(str.match(regexp))
regexp = /fox/gi
console.log(regexp.test(str))
regexp = /Heropy/gi
console.log(regexp.test(str))
regexp = /fox/gi
console.log(str.replace(regexp, 'AAA'))
console.log(str)
const h =` the hello world !
`
console.log(h.replace(/\s/g, ''))
4. 정규표현식을 사용하는 메소드 (예시는 바로 위에)
매소드 | 문법 | 설명 |
---|
test | 정규식.test(문자열) | 일치 여부(Boolean) 반환 |
match | 문자열.match(정규식) | 일치하는 문자의 배열(Array) 반환 |
replace | 문자열.replace(정규식, 대체문자) | 일치하는 문자를 대체 |
5. 플래그(옵션)
플래그 | 설명 |
---|
g | 모든 문자 일치(global) |
i | 영어 대소문자를 구분 않고 일치(ignore case) |
m | 여러 줄 일치(multi line) |
let str = `
010-1234-5678
thesecon@gmail.com
https://www.omdbapi.com/?apikey=7035c60c&s=frozen
The quick brown fox jumps over the lazy dog.
abcccdddd
`
console.log(str.match(/the/gi))
console.log(str.match(/./gi))
console.log(str.match(/\./gi))
console.log(str.match(/\.$/gi))
console.log(str.match(/\.$/gim))
6. 패턴(표현)
패턴 | 설명 |
---|
^ab | 줄(Line) 시작에 있는 ab와 일치 |
ab$ | 줄(Line) 끝에 있는 ab와 일치 |
. | 임의의 한 문자와 일치 |
a|b | a또는 b와 일치 |
ab? | b가 없거나 b와 일치 |
{3} | 3개 연속 일치 |
{3,} | 3개 이상 연속 일치 |
{3,5} | 3개 이상 5개 이하(3~5개) 연속 일치 |
[abc] | a 또는 b 또는 c |
[a-z] | a 부터 z사이의 문자 구간에 일치 (영어 소문자) |
[A-Z] | A 부터 Z 사이의 문자 구간에 일치 (영어 대문자) |
[0-9] | 0 부터 9 사이의 문자 구간에 일치 (숫자) |
[가-힣] | 가부터 힣 사이의 문자 구간에 일치 (한글) |
\w | 63개 문자 (Word, 대소영문52개 + 숫자 10개 +_)에 일치 |
\b | 63개 문자에 일치하지 않는 문자 경계(Boundary) |
\d | 숫자(Digit)에 일치 |
\s | 공백(Space, Tab 등)에 일치 |
(?=) | 앞쪽 일치(Lookahead) |
(?<=) | 뒤쪽 일치(Lookbehind) |
let str = `
010-1234-5678
thesecon@gmail.com
https://www.omdbapi.com/?apikey=7035c60c&s=frozen
The quick brown fox jumps over the lazy dog.
abcccdddd
`
console.log(str.match(/^t/gim))
console.log(str.match(/d$/gm))
console.log(str.match(/h..p/g))
console.log(str.match(/fox|dog/g))
console.log(str.match(/https?/g))
console.log(str.match(/d{2}/))
console.log(str.match(/d{2}/g))
console.log(str.match(/d{2,}/g))
console.log(str.match(/d{2,3}/g))
console.log(str.match(/\w{2,3}/g))
console.log(str.match(/\b\w{2,3}\b/g))
console.log(str.match(/[fox]/g))
console.log(str.match(/[0-9]{1,}/g))
console.log(str.match(/\w/g))
console.log(str.match(/\b/g))
console.log(str.match(/\bf\w{1,}\b/g))
console.log(str.match(/\d/g))
console.log(str.match(/\d{1,}/g))
console.log(str.match(/\s/g))
console.log(str.match(/.{1,}(?=@)/g))
console.log(str.match(/(?<=@).{1,}/g))