티스토리 뷰
예제1> 실수로 두 번 입력된 단어를 찾으세요
예문
This is a block of of text,
several words here are are
repeated, and and they
should not be.
결과
This is a block of of text,
several words here are are
repeated, and and they
should not be.
정규식
\b(\w+)\b\s+\b\1\b
이러한 패턴을 찾으려면 앞에서 찾은 문자열을 가리킬 수 있어야 합니다
이러한 참조를 역참조라 합니다
참조하려고 하는 패턴은 하위 표현식 () 로 묶어야 합니다
역참조는 마치 변수와 비슷하게 생각하면 좋습니다
역참조(\순서)는 앞서 나온 하위 표현식을 지칭하며 해당 표현식에 해당하는 문자열과 일치합니다
예제2> 이메일 주소를 찾아 mailto 하이퍼링크로 바꾸세요
예문
Hello, ben@forta.com is my email address
결과
Hello, <a href='mailto:ben@forta.com'>ben@forta.com</a> is my email address
정규식 (크롬 개발자도구 Console에서 실행)
var sample = "Hello, ben@forta.com is my email address"
sample.replace(/(\w+@\w+\.\w+)/, "<a href='mailto:$1'>$1</a>")
여태까지는 특정 패턴의 문자열을 검색하기만 했지만
위와같이 특정 패턴을 내가 원하는 형태로 치환할 수도 있습니다
그리고 이러한 치환하게 빈번히 유용하게 사용되는 것이 바로 역참조입니다
연습문제> 유효한 h태그를 모두 찾으세요
예문
<h1>Welcome to my Homepage</h1>
<h2>ColdFusion</h2>
<h3>Wireless</h3>
<h2>This is not valid html</h3>
결과
<h1>Welcome to my Homepage</h1>
<h2>ColdFusion</h2>
<h3>Wireless</h3>
<h2>This is not valid html</h3>
'Dev 일반 > 정규식' 카테고리의 다른 글
[정규식] 9. 최종 연습문제 (0) | 2019.05.09 |
---|---|
[정규식] 8. 전방탐색과 후방탐색 (0) | 2019.05.09 |
[정규식] 6. 반복 찾기 (0) | 2019.05.09 |
[정규식] 5. 메타 문자 사용하기 (0) | 2019.05.09 |
[정규식] 4. 문자 집합으로 찾기 (0) | 2019.05.09 |