JavaScript 정규표현식

2022. 2. 21. 14:17공부/Javascript

정규표현식, 이렇게 시작하자! | HEROPY

 

정규표현식, 이렇게 시작하자!

매일 쓰는 것도, 가독성이 좋은 것도 아니지만, 모르면 안되는 정규표현식. 저는 이렇게 공부하기 시작했습니다! (자바스크립트를 기준으로 설명합니다)

heropy.blog

위 블로그 참조.

 

정규표현식 테스트 사이트

https://regex101.com/ 

 

regex101: build, test, and debug regex

Regular expression tester with syntax highlighting, explanation, cheat sheet for PHP/PCRE, Python, GO, JavaScript, Java. Features a regex quiz & library.

regex101.com

https://regexr.com/ 

 

RegExr: Learn, Build, & Test RegEx

RegExr is an online tool to learn, build, & test Regular Expressions (RegEx / RegExp).

regexr.com

https://regexper.com/ 

 

Regexper

 

regexper.com

입력한 정규식을 하단의 문단에 적용하는 식으로 테스트 할 수 있다.

정규표현식은 JavaScript만의 문법이 아니고 다른 언어에도 사용하는 문법이다.

 

정규표현식 생성 방식

1. 생성자 함수 방식

- RegExp 생성자 함수를 호출하여 사용할 수 있다.

const regexp1 = new RegExp("^abc");
// new RegExg(표현식)

const regexp2 = new RegExp("^abc", "gi");
// new RegExg(표현식, 플래그)

2. 리터럴(Literal) 방식

- /로 감싸진 패턴을 리터럴로 사용한다.

const regexp1 = /^abc/;
// /표현식/

const regexp2 = /^abc/gi;
// /표현식/플래그

 

예제

let str = `
010-1234-5678
thesecon@gmail.com
https://www.youtube.com/watch?v=-JhoMGoAfFc
The quick brown fox jumps over the lazy dog.
abbcccdddd
hxyp
http://localhost:1234
`

여러 줄의 문장을 묶을 때는 `(백틱기호)를 이용한다.

 

메소드

메소드 문법 설명
test 정규식.test(문자열) 일치(포함) 여부(Boolean) 반환
match 문자열.match(정규식) 일치하는 문자의 배열(Array) 반환
replace 문자열.replace(정규식, 대체문자) 일치하는 문자를 대체
let str = `
010-1234-5678
thesecon@gmail.com
https://www.youtube.com/watch?v=-JhoMGoAfFc
The quick brown fox jumps over the lazy dog.
abbcccdddd
hxyp
http://localhost:1234
`

// const regexp = new RegExp('the', 'gi')
const regexp = /the/gi

// test
console.log(regexp.test(str)) // 결과: true

// match
console.log(str.match(regexp)) // 결과: ['the', 'The', 'the']

// replace
console.log(str.replace(regexp, 'AAA')) // 결과: the와 The를 모두 찾아 AAA로 바꾼 문자열 출력

str = str.replace(regexp, 'BBB')
console.log(str) // 결과: the와 The를 모두 찾아 BBB로 바꾼 문자열 출력

replace는 실행만으로는 원본이 바뀌지 않으므로 재할당 하는 방식으로 사용 가능하다.

 

플래그(옵션)

 

플래그 설명
g 모든 일치 문자 반환(global)
i 영어 대소문자를 구분 않고 일치(ignore case)
m 여러 줄 인식(multi line)

기본적으로 플래그 없이 정규식을 사용하면 일치하는 문자 중 제일 앞에 있는 것만 반환한다.

g를 사용하면 일치하는 문자를 모두 반환한다.

m은 여러 줄로 된 문자열에서 줄바꿈된 부분을 인식하여 여러줄을 인식해주는 플래그다.

let str = `
010-1234-5678
thesecon@gmail.com
https://www.youtube.com/watch?v=-JhoMGoAfFc
The quick brown fox jumps over the lazy dog.
abbcccdddd
hxyp
http://localhost:1234
`

const regexp = /the/
console.log(str.match(regexp))
// ['the',
// index: 15,
// input: '\n010-1234-5678\nthesecon@gmail.com\nhttps:....'
// groups: undefined]

플래그 없이 정규식을 사용한 경우 결과값의 배열이 [결과값, 대상 위치, 입력 문자열, 그룹]의 형태를 띈다.

const regexp = /the/g

console.log(str.match(regexp)) // 결과: ['the', 'the']

플래그에  g를 사용하면 'the'와 일치하는 모든 부분이 출력된다.

const regexp = /the/gi

console.log(str.match(regexp) // 결과: ['the', 'The', 'the']
console.log(str.match(/the/gi)) // 결과: ['the', 'The', 'the']

플래그에 gi를 사용하게 되면 대소문자가 무시되어 'the'와 'The' 모두 출력된다.

 

패턴(표현)

패턴 설명
^ab 줄(Line) 시작에 있는 ab와 일치
ab$ 줄(Line) 끝에 있는 ab와 일치
. 임의의 한 문자와 일치
a|b a 또는 b와 일치
{3} 3개 연속 일치
{3, } 3개 이상 연속 일치
{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.youtube.com/watch?v=-JhoMGoAfFc
The quick brown fox jumps over the lazy dog.
abbcccdddd
hxyp
http://localhost:1234
`

console.log(str.match(/\.$/)) // null
console.log(str.match(/\.$/gim)) // {'.'}

. 은 '임의의 한 문자와 일치'라는 패턴으로 해석 될 가능성이 있다.

. 그 자체를 해석하고 싶으면 앞부분에 \(이스케이프 문자)를 붙여 사용하면 된다.

$은 ~로 끝나는 것을 찾으라는 의미이므로 위의 코드는 . 으로 끝나는 것을 찾는 정규표현식이다.

그런데 뒤에 플래그가 없는 것은 str 전체를 그냥 한 문장으로 인식하기 때문에 마지막 백틱기호 앞에 . 이 없으므로 null이 출력된다. (마지막 벡틱기호 바로 앞부분이 str의 '끝'이다)

플래그 m을 사용하면 각 문장마다 줄바꿈 처리가 된 것을 인식하여 dog.의 .을 반환한다.

 

console.log(str.match(/.$/gim)) // 각 문장의 끝 글자를 가져온다.

console.log(
  str.match(/h..p|dog/g) // | === 또는. h__p 형태의 단어 또는 dog라는 단어를 찾는다.
)

console.log(str.match(/https?/g)) // http(s)를 찾는다.

console.log(str.match(/d{2}/g)) // dd 글자를 찾는다.
console.log(str.match(/d{2,}/g)) // 연속된 d로 이루어진 글자를 찾는다.

console.log(str.match(/\b\w{2,3}\b/g)) // 앞뒤가 특수기호 또는 공백이며 일반 글자 2~3개로 이루어진 단어를 찾는다.
// \b : 공백이나 특수문자 등 구분되는 것
// \w : 알파벳이나 숫자

console.log(str.match(/[fox]/g)) // f 또는 o 또는 x를 찾는다.
console.log(str.match(/[0-9a-z]{1,}/g)) // 0~9 또는 a~z로 이루어진 1개 이상의 단어를 찾는다.

console.log(str.match(/\bf\w{1,}/g)) // 구분기호가 앞에있으며 f로 시작하는 단어를 찾는다.

const h = `   the hello   world      !

`

console.log(
  h.replace(/\s/g, '') // 공백을 제거한다.
)
console.log(
  str.match(/.{1,}(?=@)/g) //@기호 앞에 있는 단어를 가져온다.
)
console.log(
  str.match(/(?<=@).{1,}/g) //@기호 뒤에 있는 단어를 가져온다.
)