본문 바로가기

패스트캠퍼스

정규표현식 [패스트캠퍼스 챌린지 12일차]

정규식
regexp 정규 표현식 약어
Regular Expression Expression

정규표현식이란,

문자열을 검색하고 대체하는 데 사용 가능한 일종의 형식 언어(패턴)이다

간단한 문자 검색부터 이메일, 패스워드 검사 등의 복잡한 문자 일치 기능 등을 정규식 패턴으로 빠르게 수행할 수 있다

→ 문자를 검색, 대체, 추출할 수 있는 방법을 제공
→ JS뿐만 아니라 다양한 환경에서 사용 가능
→ 여러 특수 기호 사용

어떤 역할?

  • 문자 검색 SEARCH
  • 문자 대체 REPLACE
  • 문자 추출 EXTRACT

테스트 사이트

https://regexr.com/

JS 정규식 생성

1.생성자 함수 방식

필요에 따라 사용할 일 있으니 기본적인 패턴은 알아두자

new RegExp('표현','옵션')
new RegExp('[a-z]','gi')

2.리터럴 방식

생성자 함수 방식에 비해 간편. 편함.

/표현/옵션
/[a-z]/gi

VScode 기본 예제

생성자 함수

  • the를 찾아보자
    str이라는 input데이터에서 the를 찾아서 배열로 만들어줌
    기본적으로는 제일 먼저 찾아진 the라는 단어만 배열로 만듦
// 줄바꿈 해가면서 문자데이터 작성하고 싶나? 백틱 기호 사용하세요
const str = `
010-1234-5678
thesecon@gmail.com
https://www.omdbapi.com/?apikey=7035c60c&s=frozen
The quick brown fox jumped over the lazy dog.
abbcccdddd
`
const regexp = new RegExp('the', '')
console.log(str.match(regexp))
    /*
     ['the', index: 15, input: '\n010-1234-5678\nthesecon@gmail.com\nhttps://www.omdb…k brown fox jumped over the lazy dog.\nabbcccdddd\n', groups: undefined]
    0: "the"
    groups: undefined
    index: 15
    input: "\n010-1234-5678\nthesecon@gmail.com\nhttps://www.omdbapi.com/?apikey=7035c60c&s=frozen\nThe quick brown fox jumped over the lazy dog.\nabbcccdddd\n"
    */

이 문장에서 the라는 모든 단어를 찾아서 배열 데이터로 만들고 싶으면??

const str = `
010-1234-5678
thesecon@gmail.com
https://www.omdbapi.com/?apikey=7035c60c&s=frozen
The quick brown fox jumped over the lazy dog.
abbcccdddd
`
// 두번째 인수로 g 플래그
const regexp = new RegExp('the', 'g')
console.log(str.match(regexp))
    /*
    (2) ['the', 'the']
    0: "the"
    1: "the"
    length: 2
    [[Prototype]]: Array(0)
    */

근데 잘 보면 소문자만 찾아내고 대문자로 시작하는 The는 찾질 않았네

패턴에 일치하지 않아서 검색되지 않은 거임

대문자 소문자 가리지 말고 찾아보자

const str = `
010-1234-5678
thesecon@gmail.com
https://www.omdbapi.com/?apikey=7035c60c&s=frozen
The quick brown fox jumped over the lazy dog.
abbcccdddd
`
// i 플래그 추가
const regexp = new RegExp('the', 'gi')
console.log(str.match(regexp))
    /*
    ['the', 'The', 'the']
    0: "the"
    1: "The"
    2: "the"
    length: 3
    */

리터럴 방식

const str = `
010-1234-5678
thesecon@gmail.com
https://www.omdbapi.com/?apikey=7035c60c&s=frozen
The quick brown fox jumped over the lazy dog.
abbcccdddd
`
// 생성자 함수 방식
// const regexp = new RegExp('the', 'gi') 

// 리터럴 방식
const regexp = /the/gi
console.log(str.match(regexp))

// 출력 결과는 생성자 함수와 같음

예제 문자

const str = `
010-1234-5678
thesecon@gmail.com
https://www.omdbapi.com/?apikey=7035c60c&s=frozen
The quick brown fox jumped over the lazy dog.
abbcccdddd
`

메소드

메소드 문법 설명
test 정규식.test(문자열) 일치 여부 (Boolean) 반환
match 문자열.match(정규식) 일치하는 문자의 배열(Array) 반환
replace 문자열.replace(정규식, 대체문자) 일치하는 문자를 대체

test

const str = `
010-1234-5678
thesecon@gmail.com
https://www.omdbapi.com/?apikey=7035c60c&s=frozen
The quick brown fox jumped over the lazy dog.
abbcccdddd
`

const regexp = /fox/gi
console.log(regexp.test(str)) // true
const str = `
010-1234-5678
thesecon@gmail.com
https://www.omdbapi.com/?apikey=7035c60c&s=frozen
The quick brown fox jumped over the lazy dog.
abbcccdddd
`

const regexp = /HEROPY/gi
console.log(regexp.test(str)) // false

replace

원본을 손상시키지 않음

const str = `
010-1234-5678
thesecon@gmail.com
https://www.omdbapi.com/?apikey=7035c60c&s=frozen
The quick brown fox jumped over the lazy dog.
abbcccdddd
`

const regexp = /fox/gi
console.log(str.replace(regexp, 'AAA'))
/*
010-1234-5678
thesecon@gmail.com
https://www.omdbapi.com/?apikey=7035c60c&s=frozen
The quick brown AAA jumped over the lazy dog.
abbcccdddd
*/
console.log(str)
/*
010-1234-5678
thesecon@gmail.com
https://www.omdbapi.com/?apikey=7035c60c&s=frozen
The quick brown fox jumped over the lazy dog.
abbcccdddd
 */

변경된 내용을 원본데이터에 저장하고 싶으면 반환된 내용을 할당해줘야 함

//const -> 재할당 가능한 let으로 바꿔줌
let str = `
010-1234-5678
thesecon@gmail.com
https://www.omdbapi.com/?apikey=7035c60c&s=frozen
The quick brown fox jumped over the lazy dog.
abbcccdddd
`

const regexp = /fox/gi

str = str.replace(regexp, 'AAA')
console.log(str)
/*
010-1234-5678
thesecon@gmail.com
https://www.omdbapi.com/?apikey=7035c60c&s=frozen
The quick brown AAA jumped over the lazy dog.
abbcccdddd
 */

플래그(옵션)

플래그 예제

마침표 찾아볼까?

정규표현식에서 마침표 기호 하나는 특정한 문자를 검색하는 일종의 패턴임

일반적인 문자로서의 마침표를 찾고 싶으면 앞에 백슬래쉬 기호 \를 붙여주자

이스케이프 문자 Escape Character란 \ (백슬래시) 기호를 통해
본래의 기능에서 벗어나 상태가 바뀌는 문자를 말한다

let str = `
010-1234-5678
thesecon@gmail.com
https://www.omdbapi.com/?apikey=7035c60c&s=frozen
The quick brown fox jumped over the lazy dog.
abbcccdddd
`

console.log(str.match(/\./gi))
//(4) ['.', '.', '.', '.']

여기서 달러 사인 $을 붙여주면?

→ 문자 데이터의 끝부분에 마침표 기호가 있는지를 일치시키는 패턴

달러 사인은 꼭 마침표 뒤에만 붙여줘야 함

$ 사인 앞에 있는 하나의 단어로 그 해당하는 문자 데이터가 끝나는 부분을 찾아서 그 부분을 일치시킨다는 뜻임

let str = `
010-1234-5678
thesecon@gmail.com
https://www.omdbapi.com/?apikey=7035c60c&s=frozen
The quick brown fox jumped over the lazy dog.
abbcccdddd
`
console.log(str.match(/\.$/gi)) // null

여기에다 multi line을 의미하는 m이란 플래그를 붙여주면?

  • 설명.
    m 플래그를 사용하지 않으면 이 문자 데이터의 가장 끝부분에 존재하는 마침표만 일치시키려고 노력하는데,
    m 플래그를 사용하면 각각의 줄에서 끝나는 부분에 마침표가 있는 부분이 있으면 그것을 찾아서 배열데이터로 만들어줌
    let str = `
    010-1234-5678
    thesecon@gmail.com
    https://www.omdbapi.com/?apikey=7035c60c&s=frozen
    The quick brown fox jumped over the lazy dog.
    abbcccdddd
    `
    console.log(str.match(/\.$/gim))

    /*
    ['.']
    0: "."
    */
  • 자세한 설명

전체의 영역에서 검색한다는 것은 g 플래그
하나의 문자데이터는 시작부분과 끝부분이 딱 하나만 존재함
그런데 문자 데이터 내부에 줄바꿈이 되어져있는 각각의 줄들을 그 줄마다
시작하고 끝나는 형태로 해석하겠다는 의미를 가짐
m 플래그는 전체 줄을 다 검색하겠다는 뜻이 아니라
각각의 줄을 하나의 시작과 끝으로 보겠다는 선언임

패턴 (표현)

패턴 설명
^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)

패턴 예제 - $

문자데이터가 d로 끝나는지 알아보기

let str = `
010-1234-5678
thesecon@gmail.com
https://www.omdbapi.com/?apikey=7035c60c&s=frozen
The quick brown fox jumped over the lazy dog.
abbcccdddd 
` //한줄 위가 아니라 바로 이 백틱 기호 앞이 문자데이터의 끝부분
console.log(
  str.match(/d$/g)
)
// null

끝나는 부분 백틱 기호 앞에 d를 넣어볼까?

let str = `
010-1234-5678
thesecon@gmail.com
https://www.omdbapi.com/?apikey=7035c60c&s=frozen
The quick brown fox jumped over the lazy dog.
abbcccdddd
d`//그래 여기
console.log(
  str.match(/d$/g)
)
//["d"]

각 줄의 시작과 끝. multi line의 m 플래그

let str = `
010-1234-5678
thesecon@gmail.com
https://www.omdbapi.com/?apikey=7035c60c&s=frozen
The quick brown fox jumped over the lazy dog.
abbcccdddd
d`
console.log(
  str.match(/d$/gm)
)
//['d', 'd'] 밑줄 친 두 녀석들

패턴 예제 - ^

줄이 t로 시작하는 부분

let str = `
010-1234-5678
thesecon@gmail.com
https://www.omdbapi.com/?apikey=7035c60c&s=frozen
The quick brown fox jumped over the lazy dog.
abbcccdddd
d`
console.log(
  str.match(/^t/gm)
)
//['t'] 소문자만 찾았네

줄이 t로 시작하는 부분 (대문자 t까지 ) i 플래그 사용

let str = `
010-1234-5678
thesecon@gmail.com
https://www.omdbapi.com/?apikey=7035c60c&s=frozen
The quick brown fox jumped over the lazy dog.
abbcccdddd
d`
console.log(
  str.match(/^t/gim)
)
//['t', 'T']

패턴 예제 - .

마침표 사용

  • 문자데이터 안에서 사용하는 대부분의 글자들과 특수기호, 띄어쓰기까지 포함
let str = `
010-1234-5678
thesecon@gmail.com
https://www.omdbapi.com/?apikey=7035c60c&s=frozen
The quick brown fox jumped over the lazy dog.
abbcccdddd
d`
console.log(
  str.match(/./g)
)
/*
['0', '1', '0', '-', '1', '2', ~~~~~~
너무 길어서 컷함.
*/

마침표 신박하게 사용 -1

let str = `
010-1234-5678
thesecon@gmail.com
https://www.omdbapi.com/?apikey=7035c60c&s=frozen
The quick brown fox jumped over the lazy dog.
abbcccdddd
d`
console.log(
  str.match(/h..p/g)
)
//['http']

마침표 신박하게 사용 -2

let str = `
010-1234-5678
thesecon@gmail.com
https://www.omdbapi.com/?apikey=7035c60c&s=frozen
The quick brown fox jumped over the lazy dog.
abbcccdddd
hppp
`
console.log(
  str.match(/h..p/g)
)
//['http','hppp']

패턴 예제 - |

fox|dog

  • a|b a 또는 b와 일치
let str = `
010-1234-5678
thesecon@gmail.com
https://www.omdbapi.com/?apikey=7035c60c&s=frozen
The quick brown fox jumped over the lazy dog.
abbcccdddd
d`
console.log(
  str.match(/fox|dog/g)
)
//['fox', 'dog']

g 플래그를 없애면?

  • a|b a 또는 b를 찾는데, 그 중에서 먼저 찾아지는 것을 반환
  • b|a 이런 식으로 순서를 바꿔도 이 중에 먼저 찾아지는 것이 반환됨
let str = `
010-1234-5678
thesecon@gmail.com
https://www.omdbapi.com/?apikey=7035c60c&s=frozen
The quick brown fox jumped over the lazy dog.
abbcccdddd
d`
console.log(
  str.match(/fox|dog/)
)
//['fox', index: 100, input: '\n010-1234-5678\nthesecon@gmail.com\nhttps://www.omdb… brown fox jumped over the lazy dog.\nabbcccdddd\nd', groups: undefined]

패턴 예제 - ?

let str = `
010-1234-5678
thesecon@gmail.com
https://www.omdbapi.com/?apikey=7035c60c&s=frozen
The quick brown fox jumped over the lazy dog.
abbcccdddd
http://localhost:1234
`
console.log(
  str.match(/https/g)
)
//['https'] 당연한 결과가 나옴

https? 물음표 기호 사용

  • 물음표 기호 앞에 글자가 있을 수도 있고 없을 수도 있고
let str = `
010-1234-5678
thesecon@gmail.com
https://www.omdbapi.com/?apikey=7035c60c&s=frozen
The quick brown fox jumped over the lazy dog.
abbcccdddd
http://localhost:1234
`
console.log(
  str.match(/https?/g)
)
//['https', 'http'] 

굉장히 많이 사용

패턴 예제 - {숫자}

let str = `
010-1234-5678
thesecon@gmail.com
https://www.omdbapi.com/?apikey=7035c60c&s=frozen
The quick brown fox jumped over the lazy dog.
abbcccdddd
http://localhost:1234
`
console.log(
  str.match(/d{2}/)
)
//['dd', index: 136, input: '\n010-1234-5678\nthesecon@gmail.com\nhttps://www.omdb…r the lazy dog.\nabbcccdddd\nhttp://localhost:1234\n', groups: undefined]]

{숫자}/g

  • g 플래그를 붙여주면?
let str = `
010-1234-5678
thesecon@gmail.com
https://www.omdbapi.com/?apikey=7035c60c&s=frozen
The quick brown fox jumped over the lazy dog.
abbcccdddd
http://localhost:1234
`
console.log(
  str.match(/d{2}/g)
)
//['dd', 'dd']

{숫자, }

  • 숫자 이상의 연속 일치
let str = `
010-1234-5678
thesecon@gmail.com
https://www.omdbapi.com/?apikey=7035c60c&s=frozen
The quick brown fox jumped over the lazy dog.
abbcccdddd
http://localhost:1234
`
console.log(
  str.match(/d{2,}/g)
)
//['dddd']

{숫자, 숫자}

let str = `
010-1234-5678
thesecon@gmail.com
https://www.omdbapi.com/?apikey=7035c60c&s=frozen
The quick brown fox jumped over the lazy dog.
abbcccdddd
http://localhost:1234
`
console.log(
  str.match(/\w{2,3}/g) 
/* \w 이게 숫자를 포함한 영어 알파벳이라구요?
숫자를 포함한 영어 알파벳이 2번 이상 3번 이하 반복되는 단어들
*/
)
/*
(42) ['010', '123', '567', 'the', 'sec', 'on', 
'gma', 'il', 'com', 'htt', 'ps', 'www', 'omd', 'bap', 
'com', 'api', 'key', '703', '5c6', '0c', 'fro', 'zen', 
'The', 'qui', 'ck', 'bro', 'wn', 'fox', 'jum', 'ped', 
'ove', 'the', 'laz', 'dog', 'abb', 'ccc', 'ddd', 'htt', 
'loc', 'alh', 'ost', '123']
*/

앙?? 위에 거랑 연관

**let str = `
010-1234-5678
thesecon@gmail.com
https://www.omdbapi.com/?apikey=7035c60c&s=frozen
The quick brown fox jumped over the lazy dog.
abbcccdddd
http://localhost:1234
`
console.log(
  str.match(/\b\w{2,3}\b/g)
)
//['010', 'com', 'www', 'com', 'The', 'fox', 'the', 'dog']**

이게 뭔 난리냐

\b \b

숫자를 포함한 영어 알파벳이 아닌 경계를 만들어 줌

이해가 안되는데요

이런 패턴을 사용해서 연속 일치 활용한다고요?


패턴 예제 - [ ]

[abc] a 또는 b 또는 c

  • [fox] fox라는 단어와 상관 없음 f, o, x 따로따로
let str = `
010-1234-5678
thesecon@gmail.com
https://www.omdbapi.com/?apikey=7035c60c&s=frozen
The quick brown fox jumped over the lazy dog.
abbcccdddd
http://localhost:1234
`
console.log(
  str.match(/[fox]/g)
)
/*
['o', 'o', 'o', 'o', 'f', 'o', 'o', 
'f', 'o', 'x', 'o', 'o', 'o', 'o']
*/

[0-9] | 0부터 9 사이의 문자 구간에 일치(숫자)

let str = `
010-1234-5678
thesecon@gmail.com
https://www.omdbapi.com/?apikey=7035c60c&s=frozen
The quick brown fox jumped over the lazy dog.
abbcccdddd
http://localhost:1234
`
console.log(
  str.match(/[0-9]/g)
)
/*
['0', '1', '0', '1', '2', '3', '4', '5', '6', 
'7', '8', '7', '0', '3', '5', '6', '0', '1', '2', '3', '4']
*/
  • [0-9]{1,} // 숫자 하나 이상이 연속되는 부분
let str = `
010-1234-5678
thesecon@gmail.com
https://www.omdbapi.com/?apikey=7035c60c&s=frozen
The quick brown fox jumped over the lazy dog.
abbcccdddd
http://localhost:1234
`
console.log(
  str.match(/[0-9]{1,}/g)
)
//['010', '1234', '5678', '7035', '60', '1234']

[가-힣] | 가부터 힣 사이의 문자 구간에 일치(한글)

let str = `
010-1234-5678
thesecon@gmail.com
https://www.omdbapi.com/?apikey=7035c60c&s=frozen
The quick brown fox jumped over the lazy dog.
abbcccdddd
http://localhost:1234
동해물과 백두산이 마르고 닳도록
`
console.log(
  str.match(/[가-힣]{1,}/g)
)
//['동해물과', '백두산이', '마르고', '닳도록']

패턴 예제 \

\w

let str = `
010-1234-5678
thesecon@gmail.com
https://www.omdbapi.com/?apikey=7035c60c&s=frozen
The quick brown fox jumped over the lazy dog.
abbcccdddd
http://localhost:1234
동해물과_백두산이 마르고 닳도록
`
console.log(
  str.match(/\w/g)
)

\b

이 사이사이의 경계. 바운더리

```jsx
let str = `
010-1234-5678
thesecon@gmail.com
https://www.omdbapi.com/?apikey=7035c60c&s=frozen
The quick brown fox jumped over the lazy dog.
abbcccdddd
http://localhost:1234
동해물과_백두산이 마르고 닳도록
`
console.log(
  str.match(/\bf\w{1,}\b/g)
)
//['frozen', 'fox']
/*
바운더리에서 시작
f라는 알파벳으로 시작하고 
63개 문자중에 1개 이상 연속 일치
바운더리에서 끝남
*/

\d 숫자(Digit)에 일치

let str = `
010-1234-5678
thesecon@gmail.com
https://www.omdbapi.com/?apikey=7035c60c&s=frozen
The quick brown fox jumped over the lazy dog.
abbcccdddd
http://localhost:1234
동해물과_백두산이 마르고 닳도록
`
console.log(
  str.match(/\d/g)
)
//['0', '1', '0', '1', '2', '3', '4', '5', '6', '7', '8', '7', '0', '3', '5', '6', '0', '1', '2', '3', '4']
  • 숫자 1개 이상
let str = `
010-1234-5678
thesecon@gmail.com
https://www.omdbapi.com/?apikey=7035c60c&s=frozen
The quick brown fox jumped over the lazy dog.
abbcccdddd
http://localhost:1234
동해물과_백두산이 마르고 닳도록
`
console.log(
  str.match(/\d{1,}/g)
)
//['010', '1234', '5678', '7035', '60', '1234']

\s 공백(Space, Tab 등)에 일치

let str = `
010-1234-5678
thesecon@gmail.com
https://www.omdbapi.com/?apikey=7035c60c&s=frozen
The quick brown fox jumped over the lazy dog.
abbcccdddd
http://localhost:1234
동해물과_백두산이 마르고 닳도록
`
console.log(
  str.match(/\s/g)
)
//['\n', '\n', '\n', '\n', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '\n', '\n', '\n', ' ', ' ', '\n']
  • 이걸 어찌 활용하나
    const h  = `  the hello  world   !
    

`
console.log(
h.match(/\s/g)
)
//[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '\n', '\n']


- replace!

```jsx
const h  = `  the hello  world   !

`
console.log(
  h.replace(/\s/g, '')
)
//thehelloworld!

패턴 예제 (?=) (?<=)

(?=) 앞쪽 일치 패턴
이메일 주소에서 아이디만 알고싶어

const str = `
010-1234-5678
thesecon@gmail.com
https://www.omdbapi.com/?apikey=7035c60c&s=frozen
The quick brown fox jumped over the lazy dog.
abbcccdddd
`

console.log(
  str.match(/.{1,}(?=@)/g) //골뱅이 앞에 백슬래시 붙여도 되고 안 붙여도 되고
)
//['thesecon']

(?<=)뒤쪽 일치 패턴

  • 음... 골뱅이 뒤쪽 이메일 주소가 나올 줄 알았는데
const str = `
010-1234-5678
thesecon@gmail.com
https://www.omdbapi.com/?apikey=7035c60c&s=frozen
The quick brown fox jumped over the lazy dog.
abbcccdddd
`

console.log(
  str.match(/.{1,}(?<=@)/g) 
)
//['thesecon@']
  • .{1, } 이녀석 위치 뒤로
const str = `
010-1234-5678
thesecon@gmail.com
https://www.omdbapi.com/?apikey=7035c60c&s=frozen
The quick brown fox jumped over the lazy dog.
abbcccdddd
`

console.log(
  str.match(/(?<=@).{1,}/g) 
)
//['gmail.com']


매는 한방에 맞으라고
미루지 않고 오늘 다 들어버렸다
그런데 그 한방이 너무 세다...


https://bit.ly/37BpXiC
본 포스팅은 패스트캠퍼스 환급 챌린지 참여를 위해 작성되었습니다.
#직장인인강 #직장인자기계발 #패스트캠퍼스 #패스트캠퍼스후기 #패캠챌린지 #한번에끝내는프론트엔드개발초격차패키지Online