이 외계어 같은 정규식을 보면 차라리 정규식 여러 개를 쓰는 함수가 낫겠다 싶기도 할 겁니다.
최소한 읽기는 쉬우니까요. 그리고 이 예제만 보면 사실 필자도 그 의견에 동의합니다. 하지만
이 예제는 룩어헤드와 부정형 룩어헤드의 중요한 사용법을 잘 보여줍니다. 룩어헤드는 분명 고
급 정규식에 속하지만, 특정한 타입의 문제를 해결할 때는 아주 유용하게 쓸 수 있습니다.
17.20
동적으로 정규식 만들기
이 장 초반에서
RegExp
생성자보다는 정규식 리터럴을 쓰는 편이 좋다고 했었습니다. 정규식
리터럴을 쓰면 타이핑하는 수고도 덜 수 있고, 자바스크립트 문자열에서 으레 하는 역슬래시를
사용한 이스케이프도 줄어듭니다. 하지만
RegExp
생성자가 필요할 때도 있는데, 동적으로 정
규식을 만들어야 할 때가 그런 경우입니다. 예를 들어 사용자 이름의 배열이 있고 문자열에서
그 배열을 사용해 일치하는 사용자 이름을 찾고 싶다고 합시다. 정규식 리터럴만 써서는 사용
자 이름을 알아낼 방법이 없습니다. 다음 예제를 보십시오.
const
users
= ["
mary
", "
nick
", "
arthur
", "
sam
", "
yvette
"];
const
text
= "
User
@
arthur
started
the
backup
and
15
:
15
, " +
"
and ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month, and much more.
O’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
I wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
I’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
I'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.