본문으로 건너뛰기
2022. 9. 14
© WONKOOK LEE

정규표현식(Regular Expression) 반복 패턴 활용 | Part 2

Using Repetition in Reguar Expressions

Indicating Character Repetition

1) +

Matches one or more occurences. 하나 또는 그 이상의 패턴 일치

2) ?

Matches zero or one occurrences. 일치하는 패턴이 없거나 하나의 패턴 일치

3) *

Matches zero or more occurrences. 일치하는 패턴이 없거나 하나 이상의 패턴 일치


Infinite Error

/s[a-z]*/g;

*처럼 ‘일치하는 패턴이 없어도’ 성립하는 수량자는 길이 0의 매치를 만들 수 있다. 길이 0 매치가 가능한 g 플래그 정규식을 exec 루프에 사용하면 lastIndex가 전진하지 않아 무한 루프에 빠질 수 있다. 에러가 발생하는 것이 아니라 루프가 멈추지 않는 것이기 때문에 버그를 알아채기 어렵다.


Greediness and Laziness in Regular Expression

기본적으로 정규표현식은 할 수 있는 한 최대한 일치 패턴을 찾으려고 하기 때문에 ‘Greedy’하다고 한다.

1) Greediness of Regular Expression

아래 상황에서 <p>.*<\/p><p>.+<\/p>는 똑같이 동작한다. 최대한 많이 일치시키려고한다.

2) Laziness of Regular Expression

/<p>.*?<\/p>/ 하나의 태그 요소를 선택한다. 중간에 와일드카드가 있더라도 닫는 p 태그가 있으면 일치 연산을 멈춘다.


Specifying Repitition Amount

1) {min, max}

Matches min to max occurrences.

2) {min}

Matches min occurrences.

3) {min, }

Matches min or more occurrences.

Examples

3개 이상 5개 이하의 문자셋 일치 연산

/\w{3,5}/g;

문자 1개 + 문자셋 3개 이상 5개 이하

/\w\w{3,5}/g;

문자셋 3개

/\w{3}/g;

문자 연속 3개와 하이픈으로 이루어진 패턴

/\w{3}-/g;

문자 3개 혹은 그 이상

/\w{3,}/g;

16진법 코드 찾는 패턴

/#[0-9A-F]{6}/g;

사회보장번호(SSN) 찾는 패턴

/\d{3}-\d{2}-\d{4}/g;

Revisiting Greedy and Lazy Concepts

Understanding that by default they're greedy, but we can force them to be lazy as if it.

What are the two functions of the ? in regular expressions?

A repetition character for matching 0 or 1 occurrence and it forces the left expression to be lazy.

const phone = document.getElementById("phone");
const regPhone = /^(\+\w{1,2})?[\s-.]?\(?\d{3}\)?[\s-.]?\d{3}?[\s-.]?\d{4}$/;

phone.addEventListener("keyup", (e) => {
console.log(e.target.value);
console.log(regPhone.test(e.target.value));
if (!!regPhone.exec(e.target.value)) {
phone.classList.remove("red");
phone.classList.add("green");
} else {
phone.classList.add("red");
phone.classList.remove("green");
}
});
좋은 사람들과 재미있는 일을 하며 열정적이고 즐겁게 살고 싶은 개발자