본문 바로가기
개발공부 일지/코테

프로그래머스 - 핸드폰 번호 가리기(JS, 자바스크립트)(정규표현식-전방탐색)

by Box Cat 2023. 2. 2.
728x90
반응형

 

https://school.programmers.co.kr/learn/courses/30/lessons/12948

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

1
2
3
function solution(phone_number) {
    return phone_number.replace(/\d(?=\d{4})/g,"*");
}
cs

 

*정규표현식 - 전방탐색

?= 는 정규표현식의 전방탐색을 의미한다.

 

?=를 사용하면, ?=가 들어있는 ()안의 표현 앞에  반드시 위치해야 하지만, ?= 바로 뒤의 있는 표현은 표함하지 않는 것을 의미한다. 

(What it's saying is that the captured match must be followed by whatever is within the parentheses but that part isn't captured.)

 

예를 들어, 

 

\d+(?=\.\w+$)

에서

\. 앞에 위치한 숫자를 찾아야 하지만, \. 자체는 포함하지 않는다. (\. 는 문자 마침점(.)을 의미한다 )

(cf.    '.'(마침표)는 모든글자 1글자를 의미한다.)

 

ex)

file4.txt => 4

file123.txt => 123

demo.3.js => 3 

이 반환되는 것을 알 수 있다.(.을 포함하지 않았다는 것에 유의!)

1
2
3
4
5
6
7
function solution(str){
   return str.match(/\d+(?=\.\w+$)/);
}
console.log(solution("file4.txt"))
console.log(solution("file123.txt"))
console.log(solution("demo.3.js"))
cs

 

출처: https://stackoverflow.com/questions/1570896/what-does-mean-in-a-regular-expression

 

What does ?= mean in a regular expression?

May I know what ?= means in a regular expression? For example, what is its significance in this expression: (?=.*\d).

stackoverflow.com

 

728x90
반응형

댓글