본문 바로가기

Dev. Web/자바스크립트 빡독!

유용한 정규 표현식

1. 파일 확장자 찾기

var testString = 'The file is logo.gif' // 원본 문자열
var regex = /\S*\.gif/i;
var results = testString.match(regex);
var file = results[0]; // logo.gif

\.gif : gif를 찾아라
\S*    : 공백이 아닌 모든 문자
i      : 대소문자 구분 없음


2. 특정 단어 찾기 ex) Apr

var sentence = 'April is the cruelest month.';
var aprMatch = /Apr(il)?\b/;

if(sentence.search(aprMatch) != -1) {
// Apr 또는 April을 찾았을 때
} else {
// 찾지 못함
}


Apr은 반드시 있어야 함
(il)? 선택적 옵션, 물음표는 아예 없거나 한 번 나타나야 함을 의미
\b : 단어의 끝에 일치함


3. URL 패턴

// URL 포함 문자열 생성
var text = '지엔선의 신간은 http://ji-n-son.co.kr 에서 확이하세요';
// 정규 표현식 생성
var urlRegex = /((\bhttp?:\/\/)|(\bwww\.))\S*/;
var url = text.match(urlRegex);
console.log(url[0]);


4. 여러개의 패턴 찾기

var text = 'there are a lot of great web sites like www.missingmanuals.com and http://www.oreeilly.com';
var urlRegex = /((\bhttp?:\/\/)|(\bwww\.))\S*/g;
var url = text.match(urlRegex);
console.log(url[0]);
console.log(url[1]);

전역 속성은 정규 표현식 생성 , 끝에 g를 붙여서 사용한다.
대소문자 구분 없이 검색하기 위해 i를 붙이는 것과 같은 방식이다.


5. 텍스트 치환

문자열.replace(정규표현식, '바꿀 문자열');

var date = '2018.12.31';
var replaceRegex = /\./g;
date = date.replace(replaceRegex, '/');
console.log(date);


6. HTML 태그 찾기

var tagRegex = /^[^<]*(<.+>)[^>]*$/.exec('<html>');

1) 문자열이나 '<' 문자를 제외한 문자나 문자열로 시작하고,
2) 중간에 태그(<>) 형태의 문자나 문자열이 있으며,
3) 빈 문자열이나 '>' 문자를 제외한 문자나 문자열로 끝난다.



US Zip Code REGEX
var ZipCode = /\d{5}(-\d{4})?/;
if you want to make sure the string ONLY contains a Zip Code use the ^ and $ to match the beginning and ending of the string like this:
var ZipCode = /^\d{5}(-\d{4})?$/;

US Phone Number REGEX
var phoneNum = /\(?(\d{3})\)?[ -.](\d{3})[ -.](\d{4})/;
if you want to make sure the string ONLY contains a phone number use the ^ and $ to match the beginning and ending of the string like this:
var ZipCode = /^\(?(\d{3})\)?[ -.](\d{3})[ -.](\d{4})$/;

Email Address REGEX
var email = /[-\w.]+@([A-z0-9][-A-z0-9]+\.)+[A-z]{2,4}/;
if you want to make sure the string ONLY contains an email address use the ^ and $ to match the beginning and ending of the string like this:
var email = /^[-\w.]+@([A-z0-9][-A-z0-9]+\.)+[A-z]{2,4}$/;

Date REGEX
var date = /([01]?\d)[-\/ .]([0123]?\d)[-\/ .](\d{4})/;
if you want to make sure the string ONLY contains a date use the ^ and $ to match the beginning and ending of the string like this:
var date = /^([01]?\d)[-\/ .]([0123]?\d)[-\/ .](\d{4})$/;

URL REGEX
var URL = /((\bhttps?:\/\/)|(\bwww\.))\S*/;
if you want to make sure the string ONLY contains a URL use the ^ and $ to match the beginning and ending of the string and remove the \b characters like this:
var URL = /^((https?:\/\/)|(www\.))\S*$/;


http://www.regexlib.com     정규표현식 라이브러리