티스토리 뷰

 

예제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>

 

 

 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함