1. 정규표현식이란?
문자열 중 특정 규칙을 가지고 있는 문자열을 검색하기 위해 사용하는 식.
2. 생성하는 방법
1. 정규표현식 리터럴을 활용한 생성
const regStr = /abc/;
console.log(regStr) // /abc/
2. RegExp객체를 활용한 생성
const regStr = new RegExp("abc");
console.log(regStr) // /abc/
3. 기본형태
const regEx = /pattern/flag
Pattern은 일치하는 문자를 찾기 위한 식을 쓴다.
flag는 검색 설정을 변경할 수 있다.
4. Pattern 상세
- 문자열 찾기
/문자열/
슬래시 안에 문자열을 입력하게 되면 해당 문자열이 존재하는 것을 찾게 된다.
즉 지금 /문자열/이라고 입력했으므로 긴 문자 중 '문자열'을 모두 찾는다.
const str = '안녕하세요 문자열입니다. 문자열이 얼마나 들어있는지 확인 해보고 싶습니다.'
const matched = str.match(/문자열/g)
console.log(matched) //['문자열', '문자열']
const matched2 = str.match(/니다/g)
console.log(matched2) //['니다', '니다']
- 숫자 일치
\d
숫자가 한 개 라도 포함되어있다면 해당 숫자를 return 한다.
const str = 'abc123xyz'
const matched = str.match(/\d/g) //g플래그는 문자열 모두 검색 하겠다는 플래그
console.log(matched); // ['1', '2', '3']
- 숫자제외 모든것
\D
숫자 제외한 모든 것을 return한다.
const str = 'abc123xyz!@#&'
const matched = str.match(/\D/g)
console.log(matched) // ['a', 'b', 'c', 'x', 'y', 'z', '!', '@', '#', '&']
- 모든 문자열, 공백, 숫자, 기호 매칭
.
const str = 'abc123.xyz!@#&.'
const matched = str.match(/./g)
console.log(matched) // ['a', 'b', 'c', '1', '2', '3', '.', 'x', 'y', 'z', '!', '@', '#', '&', '.']
- 실제 문자 '.' 매칭 (이스케이프 해야 함)
\.
const str = 'abc123xyz!.@#&.'
const matched = str.match(/\./g)
console.log(matched) //['.', '.']
- 글자 하나씩 매칭되는 것 모두
[abc]
1. [abc] - a나 b나 c 중 하나와 매칭
const str = 'abc123.xyz!@#&.'
const matched = str.match(/[abc]/g)
console.log(matched) //['a', 'b', 'c']
2. [cmf]an - c나 m나 f 뒤에 an이 오는 패턴과 매칭
const strArr = ['can', 'man', 'fan', 'dan', 'ran', 'pan']
for (let str of strArr) {
console.log(str.match(/[cmf]an/g))
}
// ['can']
// ['man']
// ['fan']
- 패턴내 모든 글자를 제외한 모든 글자들
[^abc]
const str = 'abc123.xyz!@#&.'
const matched = str.match(/[^abc]/g)
console.log(matched) //['1', '2', '3', '.', 'x', 'y', 'z', '!', '@', '#', '&', '.']
const strArr = ['hog', 'dog', 'bog']
for (let str of strArr) {
if (str.match(/[^bog]/g)) {console.log(str)}
}
//hog
//dog
- 문자의 범위
[a-z]
시작이 대문자 나머지는 소문자인 세글자 문자 찾기 ({}패턴은 조금 뒤에)
const strArr = ['Ana', 'Bob', 'Cpc', 'aax', 'bby', 'ccz']
for (let str of strArr) {
if (str.match(/[A-Z][a-z]{2}/g)) {console.log(str)}
}
- 특정 문자범위 제외
[^n-p]
const str = 'abc1nopr23xyz!.@#&'
const matched = str.match(/[^n-p]/g)
console.log(matched) //['a', 'b', 'c', '1', 'r', '2', '3', 'x', 'y', 'z', '!', '.', '@', '#', '&']
- 특정 문자 반복
문자{횟수}
w{3} // w가 3번 반복
[wxy]{5} // w, x, y 중 하나가 5번 반복
.{2,6} // 어떤 문자든 2번에서 6번 반복
- 특정문자 0번 혹은 1번이상 반복
문자+ //1번이상 반복
문자* //0번이상 반복
ab가 1번이상, c가 0번이상 반복
const strArr = ['abc', 'abcdabc', 'Cpc', 'aax', 'bby', 'ccz', '']
for (let str of strArr) {
if (str.match(/abc*/g)) {console.log(str)}
}
//abc
//abcabc
abc중 한 글자가 0번이상 반복
const strArr = ['abc', 'abcdabc', 'Cpc', 'aax', 'bby', 'ccz', '']
for (let str of strArr) {
if (str.match(/(abc)*/g)) {console.log(str)}
}
//abc
//abcabc
//Cpc
//aax
//bby
//ccz
글자 abc가 1번이상 반복
const strArr = ['abc', 'abcdabc', 'Cpc', 'aax', 'bby', 'ccz', '']
for (let str of strArr) {
if (str.match(/(abc)+/g)) {console.log(str)}
}
//abc
//abcabc
-특정 문자 옵셔널
?
숫자1혹은 2자리 + 공백 + 'file'+ 's'옵셔널 + 공백 + 'found' + ? (문자 물음표)
const strArr= ['1 file found?', '2 files found?', '24 files found?', 'No files found.']
for (let str of strArr) {
if(str.match(/\d\d?\sfiles?\sfound\?/)) {
console.log(str)
}
}
//1 file found?
//2 files found?
//24 files found?
- 공백
\s
숫자 + . + 공백 1개이상 + 숫자이외의 모든것 1개이상
const strArr= ['1. abc', '2. abc', '3. abc', '4.abc']
for (let str of strArr) {
if(str.match(/\d\.\s+\D+/g)) {
console.log(str)
}
}
//1. abc
//2. abc
//3. abc
- 공백없음
\S
숫자 + . + 공백 없음 + 숫자이외의 모든것 1개이상
const strArr= ['1. abc', '2. abc', '3. abc', '4.abc']
for (let str of strArr) {
if(str.match(/\d\.\S\D+/g)) {
console.log(str)
}
}
//4.abc
- 특정문자로 시작 혹은 끝
^ //시작
$ //끝
Mission글자로 시작해서 successful로 끝나는 문자
const strArr= ['Mission: successful', 'Last Mission: unsuccessful', 'Next Mission: successful upon capture of target']
for (let str of strArr) {
if(str.match(/^Mission.*successful$/g)) {
console.log(str)
}
}
//Mission: successful
참고자료
코딩교육 티씨피스쿨
4차산업혁명, 코딩교육, 소프트웨어교육, 코딩기초, SW코딩, 기초코딩부터 자바 파이썬 등
tcpschool.com
RegexOne - Learn Regular Expressions - Lesson 1: An Introduction, and the ABCs
Regular expressions are extremely useful in extracting information from text such as code, log files, spreadsheets, or even documents. And while there is a lot of theory behind formal languages, the following lessons and examples will explore the more prac
regexone.com
'TIL' 카테고리의 다른 글
useEvent 제안의 배경과 중단된 이유 (0) | 2025.03.10 |
---|---|
jsdom과 jest-dom 그리고 testing-library (0) | 2025.01.12 |
[espree] espree를 사용해서 jsx를 파싱 해보기 (0) | 2025.01.08 |
createRoot (0) | 2024.12.16 |
TIL pub sub 패턴 (0) | 2024.06.23 |