강의노트 - 28

김희목·2024년 7월 24일
0

패스트캠퍼스

목록 보기
35/53

정규표현식(RegExp, Regulasr Expression)

-문자 검색(Search) / 문자 대체(Replace) / 문자 추출(Extract)

생성자

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

리터럴

  • /표현/옵션 => /[a-z]/gi
const str = `
  010-1234-5678
  thesecon@gmail.com
  Hello world!
  https://www.omdbpai.com/?apikey=705c60c&s=frozen
  The quick brown fox jumps over the lazy dog.
  hello@naver.com
  http://localhost:1234
  동해물과 백두산이 마르고 닳도록
  abbcccddddeeeee
`

// const regexp = new RegExp('the', 'gi')
// console.log(str.match(regexp))

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

정규식 메소드

정규식.text(문자열) - 일치 여부 반환
문자열.match(정규식) - 일치하는 문자의 배열 반환
문자열.replace(정규식, 대체문자) - 일치하는 문자를 대체

const str = `
  010-1234-5678
  thesecon@gmail.com
  Hello world!
  https://www.omdbpai.com/?apikey=705c60c&s=frozen
  The quick brown fox jumps over the lazy dog.
  hello@naver.com
  http://localhost:1234
  동해물과 백두산이 마르고 닳도록
  abbcccddddeeeee
`

const regexp = /fox/gi

console.log(regexp.test(str))
console.log(str.match(regexp))
console.log(str.replace(regexp, 'cat'))

정규식 플래그

g - 모든 문자 일치(Global)
i - 영어 대소문자를 구분 않고 일치(Ignore case)
m - 여러 줄 일치(Multi line), 각각의 줄을 시작과 끝으로 인식!

const str = `
  010-1234-5678
  thesecon@gmail.com
  Hello world!
  https://www.omdbpai.com/?apikey=705c60c&s=frozen
  The quick brown fox jumps over the lazy dog.
  hello@naver.com
  http://localhost:1234
  동해물과 백두산이 마르고 닳도록
  abbcccddddeeeee
`

console.log(str.match(/the/))
console.log(str.match(/the/g))
console.log(str.match(/the/gi))
console.log(str.match(/\.$/gi)) // 이스케이프 문자, 닷을 찾기 위해서 앞에 백슬래시 기호를 사용
console.log(str.match(/\.$/gim))

0개의 댓글