"Boldness has genius, power, and magic in it." - Johann Wolfgang von Goethe

JavaScript

[JS] JavaScript 정규표현식 메소드,표현 정리

Toproot 2021. 8. 23. 13:58
728x90
728x90

📝정규표현식이란?

정규 표현식은 문자열에 나타는 특정 문자 조합과 대응시키기 위해 사용되는 패턴입니다.

자바스크립트에서, 정규 표현식 또한 객체입니다.  이 패턴들은 RegExp exec 메소드와 test 메소드

 그리고 String의  match메소드 , replace메소드 , search메소드 ,  split 메소드와 함께 쓰입니다 .

 

정규 표현식 - JavaScript | MDN

정규 표현식은 문자열에 나타는 특정 문자 조합과 대응시키기 위해 사용되는 패턴입니다. 자바스크립트에서, 정규 표현식 또한 객체입니다.  이 패턴들은 RegExp의 exec 메소드와 test 메소드  ,

developer.mozilla.org

 

 

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

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

heropy.blog

 

연습사이트

https://regexr.com/

 

RegExr: Learn, Build, & Test RegEx

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

regexr.com

 

 

📝정규식 생성

// 1. 생성자
new RegExp('표현', '옵션')
new RegExp('[a-z]', 'gi)


// 2. 리터럴
/표현/옵션
/[a-z]/gi

 

 

📝메소드

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

// 생성자방식('표현','옵션')
// const regexp = new RegExp('the', 'g')
// 정규표현식(리터럴 방식)

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

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

// replace
console.log(str.replace(regexp, 'AAA')) // The quick brown AAA jumps over the lazy dog.

 

 

📝플래그(옵션)

이스케이프 문자(Escape Character)란 

\(백슬래시) 기호를 통해 본래의 기능에서 벗어나 상태가 바뀌는 문자를 말합니다.

// \(백슬래쉬)
console.log(str.match(/\./gi))

// $ : 마침표로 끝나는 부분이 있으면 그 마침표 반환. + m(multi line)
console.log(str.match(/\.$/gim))

 

 

📝패턴(표현) (1)

// . : 임의의 한 문자와 일치
console.log(
  str.match(/h..p/g)
)

// | : 또는, a또는 b와 일치
console.log(
  str.match(/fox|dog/g)
)

// ab? : b가 없거나 b와 일치, 물음표 앞의 한글자가 있을 수 도 없을 수도
console.log(
  str.match(/https?/g)
)

// {3} : 3개 연속 일치
console.log(
  str.match(/d{2}/) // dd
)

// {3,} : 3개 이상 연속 일치
console.log(
  str.match(/d{2,}/) // dd
)

// {2,3} :2개 이상 3개 이하(2~3개) 연속 일치
console.log(
  str.match(/d{2,3}/g) // dd
)

// {2,3} : 2개 이상 3개 이하(2~3개) 연속 일치
console.log(
  str.match(/\b\w{2,3}\b/g) // dd
)
// (8) ["010", "com", "www", "com", "The", "fox", "the", "dog"]

 

📝패턴(표현) (2)

// [abc] : a또는 b또는 c
console.log(
  str.match(/[fox]/g) // f 또는 o 또는 x
)

// 숫자 1개이상이 연속되는 모든 숫자들을 구분해서 출력
console.log(
  str.match(/[0-9]{1,}/g) // ["010", "1234", "5678", "7035", "60", "1234"]
)

// 한글 1개이상이 연속되는 모든 한글들을 구분해서 출력
console.log(
  str.match(/[가-힣]{1,}/g)
)

// 소문자 f로 시작하는 모든 영단어 찾기
console.log(
  str.match(/\bf\w{1,}\b/g) //  ["frozen", "fox"]
)


// 공백 제거
const h = `  the hello  world     !

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


// @ 앞쪽의 문자 가져오기
console.log(
  str.match(/.{1,}(?=@)/g)
)

// @ 뒤쪽의 문자 가져오기
console.log(
  str.match(/(?<=@).{1,}/g)
)

 

 

 

728x90
728x90