문자열을 검색하고 대체하는 데 사용 가능한 일종의 형식 언어(패턴)이다.
🤔 정규표현식 테스트 사이트
https://regex101.com/
https://regexr.com/
https://regexper.com/
a~z 영어 소문자를 검색하는 패턴이다.
new RegExp('표현', '옵션')
new RegExp('[a-z]', 'gi')
input
에서 패턴으로 입력한 the
를 찾아서 배열로 반환한다.
const str = `
010-1234-5678
thesecon@gmail.com
https://www.omdbapi.com/?apikey=7035c60c&s=frozen
The quick brown fox jumps over the lazy dog.
abbcccdddd
`
const regexp = new RegExp('the', '')
console.log(str.match(regexp))
👉 실행 결과
최초로 찾은 the
만 반환되었는데, input
에서 모든 the
를 찾아서 배열을 만들어보자.
옵션에 g
플래그를 추가하였다.
const regexp = new RegExp('the', 'g')
👉 실행 결과
이때 우리가 str
에 저장한 문자열 중에는 the
가 3개 있는데 2개만 검색되었다.
이는 The quick ...
부분의 The
가 대문자로 시작하므로 인식하지 못한 것이다.
따라서 옵션에 i
플래그를 추가하였다.
const regexp = new RegExp('the', 'gi')
👉 실행 결과
/표현/옵션
/[a-z]/gi
const str = `
010-1234-5678
thesecon@gmail.com
https://www.omdbapi.com/?apikey=7035c60c&s=frozen
The quick brown fox jumps over the lazy dog.
abbcccdddd
`
// const regexp = new RegExp('the', 'gi')
const regexp = /the/gi
console.log(str.match(regexp))
👉 실행 결과
생성자 방식과 같은 결과나 출력된 것을 알 수 있다.
메소드 | 문법 | 설명 |
---|---|---|
test | 정규식.test(문자열) | 일치 여부 반환 |
match | 문자열.match(정규식) | 일치하는 문자열의 배열 반환 |
replace | 문자열.replace.(정규식,대체문자) | 일치하는 문자열을 대체하고 대체된 문자열 반환 |
.test()
const regexp = /fox/gi
console.log(regexp.test(str))
👉 실행 결과
.replace()
const regexp = /fox/gi
console.log(str.replace(regexp, 'AAA'))
👉 실행 결과
원본 데이터를 손상시키지 않는다.
플래그 | 설명 |
---|---|
g | 모든 문자 일치(global) |
i | 영어 대소문자를 구분 않고 일치(ignore case) |
m | 여러 줄 일치(multi line) |
g
플래그const str = `
010-1234-5678
thesecon@gmail.com
https://www.omdbapi.com/?apikey=7035c60c&s=frozen
The quick brown fox jumps over the lazy dog.
abbcccdddd
`
const regexp = /the/g
console.log(str.match(regexp))
👉 실행 결과
g
플래그를 이용해 모든 'the'를 찾아냈지만, 대문자로 시작하는 'The quick ...' 부분의 'the'는 찾지 못한다.
i
플래그console.log(str.match(/the/gi))
👉 실행 결과
i
플래그를 추가하여 대소문자를 구분하지 않고 모든 'the'를 찾아냈다.
m
플래그전체 줄에서 검색하는 것이 아닌 줄 바꿈이 되어있는 각각의 줄을 하나의 시작과 끝으로 보는 것이라고 이해하면 쉽다.
const str = `
010-1234-5678
thesecon@gmail.com
https://www.omdbapi.com/?apikey=7035c60c&s=frozen
The quick brown fox jumps over the lazy dog.
abbcccdddd.
`
console.log(str.match(/\.$/gim))
👉 실행 결과
m
플래그를 붙이지 않으면 `(백틱)이 있는 마지막 줄에서만 '.'를 찾으려고 할 것이다. m
플래그를 붙임으로써 여러 줄에서 탐색하게 되었고, 'The quick ... dog.'와 'abbcccdddd.' 에서 '.'를 찾은 것이다.
🤔 이스케이프 문자
\
(백슬래시) 기호를 통해 본래의 기능에서 벗어나 상태가 바뀌는 문자를 말한다.
패턴 | 설명 |
---|---|
^ab | 줄(Line) 시작에 있는 ab와 일치 |
ab$ | 줄(Line) 끝에 있는 ab와 일치 |
. | 임의의 한 문자와 일치 |
`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, 대소영문25개 + 숫자10개 + _)에 일치 |
\b | 63개 문자에 일치하지 않는 문자 경계(Boundary) |
\d | 숫자(Digit)에 일치 |
\s | 공백(Space, Tab 등)에 일치 |
(?=) | 앞쪽 일치(Lookahead) |
(?<=) | 뒤쪽 일치(Lookbehind) |
$
패턴const str = `
010-1234-5678
thesecon@gmail.com
https://www.omdbapi.com/?apikey=7035c60c&s=frozen
The quick brown fox jumps over the lazy dog.
abbcccdddd
`
console.log(
str.match(/d$/gm)
)
👉 실행 결과
^
패턴console.log(
str.match(/^t/gm)
)
👉 실행 결과
.
패턴console.log(
str.match(/./gm)
)
👉 실행 결과
|
패턴console.log(
str.match(/fox|dog/)
)
👉 실행 결과
최초로 찾아지는 것만 반환된다.
?
패턴const str = `
010-1234-5678
thesecon@gmail.com
https://www.omdbapi.com/?apikey=7035c60c&s=frozen
The quick brown fox jumps over the lazy dog.
abbcccdddd
http://127.0.0.1:5500/index.html
`
console.log(
str.match(/https?/g)
)
👉 실행 결과
?
앞에 있는 s
가 있을 수도 있고 없을 수도 있으므로 http
와 https
를 모두 찾아낸다.
{}
패턴const str = `
010-1234-5678
thesecon@gmail.com
https://www.omdbapi.com/?apikey=7035c60c&s=frozen
The quick brown fox jumps over the lazy dog.
abbcccdddd
`
console.log(
str.match(/d{2}/g)
)
👉 실행 결과
d
가 2번 반복되는 부분을 전체에서 찾는 것이므로 abbcccdddd
에서 dd
를 2번 찾아낸다.
\b\w{}
를 활용한 예제const str = `
010-1234-5678
thesecon@gmail.com
https://www.omdbapi.com/?apikey=7035c60c&s=frozen
The quick brown fox jumps over the lazy dog.
abbcccdddd
`
console.log(
str.match(/\bf\w{1,}\b/g)
)
👉 실행 결과
\b
: 63개의 문자가 아닌 경계에서 시작하여
f
: 'f'라는 알파벳 단어로 시작하고,
w{1,}
: 뒤쪽에 63개의 문자가 1개 이상 오는 연속 일치를 시킨 다음,
\b
: 마지막에 63개의 문자가 아닌 경계에서 끝나는
단어를 찾는 것이다. (= 'f'로 시작하는 모든 영단어를 찾는다.)
const h = ` the hello world !
`
console.log(
h.replace(/\s/g, '')
)
👉 실행 결과
\s
를 이용해 공백을 찾아서 ''
로 대체(replace
)한다. (= 공백을 제거한다.)
?=
const str = `
010-1234-5678
thesecon@gmail.com
whfflek@gmail.com
gktlRMfj@gmail.com
`
console.log(
str.match(/.{1,}(?=@)/g)
)
👉 실행 결과
이메일에서 '@'를 기준으로 아이디만 찾아낼 수 있다.