본문 바로가기

Programming/Javascript

정규 표현식 메소드 및 예시

728x90

정규 표현식 리터럴

1)슬래시로 패턴을 감쌈

2)스크립트를 불러올 때 컴파일되므로, 패턴이 바뀔 일이 없을때 사용하면 성능 향상

const re = /ab+c/g;

RegExp 객체의 생성자

1)String처럼 작성

2)런타임에 컴파일되므로, 패턴이 바뀔 수 있을때 사용할 것

const re = new RegExp('ab+c', 'g');

regexObj.exec(str)

1)일치 탐색을 수행한 결과를 배열 혹은 null로 반환 및

regExpObj.lastIndex를 처음 일치하는 문자열의 마지막 문자 인덱스로 설정

2)탐색을 실패하면 null을 반환, regExpObj.lastIndex를 0으로 설정

3)RegExp생성자의 두 번째 파라미터인 플래그값이 g 또는 y일 경우

regExpObj.lastIndex를 저장

플래그 설명
d 부분 문자열 일치에 대해 인덱스 생성
g 전역 탐색
i 대소문자 구분하지 않음
m 여러 줄에 걸쳐 탐색
s 개행 문자가 .과 일치
u 유니코드 포인트의 시퀀스로 간주함
y 대상 문자열의 현재 위치에서 탐색
const regex1 = /foo*/g;
const str1 = 'table football, foosball';

console.log(regex1.exec(str1), regex1.lastIndex); // ["foot", index: 6, ..] 10
console.log(regex1.exec(str1), regex1.lastIndex); // ["foo", index: 16, ..] 19
console.log(regex1.exec(str1), regex1.lastIndex); // null 0
console.log(regex1.exec(str1), regex1.lastIndex); // ["foot", index: 6, ..] 10

regexObj.test(str)

1)일치 탐색을 수행한 결과의 일치 여부를 true 또는 false로 반환

2)RegExp생성자의 두 번째 파라미터인 플래그값이 g 또는 y일 경우

regExpObj.lastIndex를 저장

const regex1 = /foo*/g;
const str1 = 'table football, foosball';

console.log(regex1.test(str1), regex1.lastIndex); // true 10
console.log(regex1.test(str1), regex1.lastIndex); // true 19
console.log(regex1.test(str1), regex1.lastIndex); // false 0
console.log(regex1.test(str1), regex1.lastIndex); // true 10

str.match(regexp)

1)일치 탐색을 수행한 결과를 배열 혹은 null로 반환

2)regexp에 g 플래그가 포함되어 있지 않다면 regexObj.exec(str)과 동일한 결과를 반환

const str1 = 'table football, foosball';
const regex1 = /foot*/g;

str1.match(regex1); // (2) ['foot', 'foo']

str.search(regexp)

1)일치 탐색을 수행한 결과 첫 번째로 일치되는 것의 인덱스를 반환, 없다면 -1을 반환

const str1 = 'table football, foosball';
const regex1 = /foot*/g;

str1.search(regex1); // 6

※기타 정규표현식을 활용가능한 String의 메소드들

1)str.replace(regexp|substr, newSubstr|function)

2)str.split(separator)

3)숫자만 처리하는 예시

'123-4567_89'.replace(/[^0-9]/g, ''); // '123456789'
'123-4567_89'.split(/[^0-9]/); // ['123','4567','89']

참고) https://developer.mozilla.org/ko/docs/Web/JavaScript/Guide/Regular_Expressions

 

정규 표현식 - JavaScript | MDN

정규 표현식, 또는 정규식은 문자열에서 특정 문자 조합을 찾기 위한 패턴입니다. JavaScript에서는 정규 표현식도 객체로서, RegExp의 exec()와 test() 메서드를 사용할 수 있습니다. String의 match(), matchA

developer.mozilla.org

728x90

'Programming > Javascript' 카테고리의 다른 글

Javascript 프로미스 promise 비동기 async await JS  (0) 2025.03.18
엔터와 공백문자를 +와 '로 이은 문자 변환기  (0) 2023.07.17
정규 표현식  (0) 2022.06.09
JavaScript Array  (0) 2022.05.07
JavaScript loop  (0) 2022.05.06