정규표현식

SOMEmo·2022년 4월 28일
1
post-thumbnail
  1. 개요 및 프로젝트 시작
    npm init -y
    npm i parcel-bundler -D
    index.html, main.js 파일수정
    package.json에서 test부분 지우고
"dev": "parcel index.html",
"build": "parcel build index.html"

$ npm run dev


  1. 정규식 생성

자바스크립트 정규식 생성
1) 생성자 함수 방식

const regexp1 = new RegExp("6abc");
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', '')
const regexp = new RegExp('the', 'g') 모든 the찾기
const regexp = new RegExp('the', 'gi') 대소문자 구별없이 the찾기
console.log(str.match(regexp))

2) 리터럴 방식

const regexp = /the/gi
console.log(str.match(regexp))

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

test

const regexp = /fox/gi;
console.log(regexp.test(str));

replace

const regexp = /fox/gi;
//console.log(regexp.test(str));
console.log(str.replace(regexp, 'AAA'))

  1. 플래그(옵션)
플래그설명
g모든 문자 일치(global)
i영어 대소문자를 구분 않고 일치(ignore case)
m여러 줄 일치(multi line)
console.log(str.match(/the/gi))

console.log(str.match(/\.$/gim))

  1. 패턴(표현)(1)
패턴설명
^ab줄(Line) 시작에 있는 ab와 일치
ab$줄(Line) 끝에 있는 ab와 일치
.임의의 한 문자와 일치
a|ba 또는 b와 일치
ab?b가 없거나 b와 일치
{3}3개 연속 일치
{3,}3개 이상 연속 일치
{3,5}3개 이상 5개 이하(3~5개) 연속 일치
console.log(
  str.match(/d$/gm)
)

console.log(
  str.match(/^t/gim)
)

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(/\b\w{2,3}\b/g)
)

  1. 패턴(표현)(2)
패턴설명
[abc]a 또는 b 또는 c
[a-z]a부터 z 사이의 문자 구간에 일치(영어 소문자)
[A-Z]A부터 Z 사이의 문자 구간에 일치(영어 대문자)
[0-9]0부터 9 사이의 문자 구간에 일치(숫자)
[가-힣]가부터 힣 사이의 문자 구간에 일치(한글)
\w63개 문자(Word, 대소영문52개 + 숫자10개 + _)에 일치
\b63개 문자에 일치하지 않는 문자 경계(Boundary)
\d숫자(Digit)에 일치
\s공백(Space, Tav 등)에 일치
console.log(
  str.match(/[fox]/g)
)

console.log(
  str.match(/[0-9]/g)
)

console.log(
  str.match(/[0-9]{1,}/g)
)

console.log(
  str.match(/[가-힣]{1,}/g)
)

console.log(
  str.match(/\w/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)
)

h.replace(/\s/g, '')

console.log(
  str.match(/.{1,}(?=@)/g)
)

console.log(
  str.match(/(?<=@).{1,}/g)
)

0개의 댓글