웹프로그래밍

Global It Leader!!


jQuery


 
 

정규 표현식(regexp) 예 모음

페이지 정보

작성자 no_profile 오원장 쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 댓글 0건 조회 4,549회 작성일 12-04-01 07:59

본문

기본 문법

RegExp.exec(string)
RegExp.test(string)
String.match(pattern)
String.search(pattern)
String.replace(pattern,string)
String.split(pattern)

구분 문자열 설명
확장문자
(backslash)
s 공백 문자(스페이스, 탭, 폼 피드, 라인 피드)
b 단어의 경계
B 이를 제외한 모든 문자 매칭
d 숫자
D 숫자가 아닌 문자 [^0-9] 와 동일
w 알파벳, 숫자로 된 문자, 밑줄 기호(_) [A-Za-z0-9]
W w의 반대 문자 [^A-Za-z0-9]
특수문자
(특수문자 자체를 의미)
* 0회 이상 반복
+ 1회 이상 반복
 ? 0 또는 1개의 문자 매칭
. 정확히 1개 문자 매칭
플래그 g 전역매칭
i 대소문자 무시
m 여러 줄 매칭
기타 () 괄호로 묶인 패턴은 매칭된 다음, 그 부분을 기억한다.
$1,...,$9 괄호로 갭처한 부분 문자열이 저장 됨.
| ~또는~
{} 반복 횟수

간단한 정규 표현식

var re = /a/         --a 가 있는 문자열
var re = /a/i        --a 가 있는 문자열, 대소문자 구분 안함
var re = /apple/    -- apple가 있는 문자열
var re = /[a-z]/    -- a~z 사이의 모든 문자
var re = /[a-zA-Z0-9]/    -- a~z, A~Z 0~9 사이의 모든 문자
var re = /[a-z]|[0-9]/  -- a~z 혹은 0~9사이의 문자
var re = /a|b|c/   --  a 혹은 b 혹은 c인 문자
var re = /[^a-z]/  -- a~z까지의 문자가 아닌 문자("^" 부정)
var re = /^[a-z]/  -- 문자의 처음이 a~z로 시작되는 문장
var re = /[a-z]$/  -- 문자가 a~z로 끝남

상기에 정의된 간단한 표현식을 아래에 넣어 직접 해 보시기 바랍니다.

var str = "sample string";
re.test(str)?"true":"false";

특수문자('''', ''^'', ''$'', ''*'', ''+'', ''?'', ''.'', ''('', '')'', ''|'', ''{'', ''}'', ''['', '']'')를 검색할 경우는 '''' 를 넣는다.

간단한 응용예제

var re = /s$/;          -- 공백체크
var re = /^ss*$/;   -- 공백문자 개행문자만 입력 거절
var re = /^[-!#$%&'*+./0-9=?A-Z^_a-z{|}~]+@[-!#$%&'*+/0-9=?A-Z^_a-z{|}~]+.[-!#$%&'*+./0-9=?A-Z^_a-z{|}~]+$/; --이메일 체크
var re = /^[A-Za-z0-9]{4,10}$/ -- 비밀번호,아이디체크 영문,숫자만허용, 4~10자리
var re = new RegExp("(http|https|ftp|telnet|news|irc)://([-/.a-zA-Z0-9_~#%$?&=:200-377()]+)","gi") -- 홈페이지 체크

var re = "<[^<|>]*>";  -- 태그제거
var re = /[<][^>]*[>]/gi;-- 태그제거
str = str.replace(RegExpTag,"");  

var RegExpJS = "<script[^>]*>(.*?)</script>";  -- 스크립트 제거  
str = str.replace(RegExpJS,"");  

var RegExpCSS = "<style[^>]*>(.*?)";  -- 스타일 제거  
str = str.replace(RegExpCSS,"");  

var RegExpHG = "[ㄱ-ㅎ가-힣]";  -- 한글 제거  
str = str.replace(RegExpHG,"");  
 
var RegExpDS = /<!--[^>](.*?)-->/g;   -- 주석 제거  
str6 = str.replace(RegExpDS,"");  

var regExp = /[a-z0-9]{2,}@[a-z0-9-]{2,}.[a-z0-9]{2,}/i; --이메일 체크

기타 응용

문장의 처음이 @이고 문자가 1나 이상 있으면 ok

re = new RegExp("^@[a-zA-Z0-9]+s+","i");

영숫자 조합책크

if ((new RegExp(/[^a-z|^0-9]/gi)).test(frm.loginid.value)) {
    alert("ID는 영숫자 조합만 사용하세요");
    frm.loginid.focus();
}

홈페이지 주소 책크

 function chk(v){
  str='';
  re = new RegExp("^http://","i");  
  re.test(v)?str='y':str='n';
  alert(str);
 }

hanmail인지를 책크

 function chk(v){
  str='';
  re = new RegExp("hanmail.net","i");  
  re.test(v)?str=true:str=false;
  return str
 }

본문내에서 도메인 구하기

var patt = /(http(s)?://)?w+(.w+)+/gi;
var result = (aa.value.match(patt));

본문내에서 url구하기 (상기와 유사)

var patt = /(http(s)?://)?w+(.w+).S*/gi;

정규식 메소드 및 사용법


활용팁

프로그래밍하다가 소스 막기가 필요한 곳이 많아 보여서 몇개의 팁을 정리했습니다.

주의할 점은 소스에서 설정을 해 놓아도 HTML내에 Iframe이 있는 경우 Iframe안에 있는 다른 html에는 설정이 안 된다는 점입니다.

그래서 상태바에 링크 주소 막기 같은 경우는 꽁수로

function status_message()
{
  window.status = "";
}
setInterval("status_message()",1);

이런 식으로 쓰는 경우도 있습니다. 계속적으로 상태바의 주소글자를 바꿔주는 아주 안 좋은 방식입니다. (그리고 아주 잠깐은 소스가 보입니다. = =;)

아무튼 Iframe, modal 등이 아닌 곳은 다 적용됩니다.

마우스 오른쪽메뉴, 드래그, 선택복사 금지하기

<body oncontextmenu='return false' ondragstart='return false' onselectstart='return false'>
  • oncontextmenu="return false": 마우스 오른쪽 메뉴 금지
  • ondragstart="return false": 드래그 금지
  • onselectstart="return false": 선택복사 금지
  • onkeydown="return false" 키보드 완전 금지

마우스 오른쪽 버튼 클릭시 경고 메세지

document.onmousedown = function() {
    if ((event.button==2) || (event.button==2)) {
        alert('죄송합니다. 오른쪽 마우스 금지입니다.');
    }
}

shift, ctrl (쉬프트, 컨트롤)키 클릭하면 경고메세지 띄우기

function click() {
    if((event.ctrlKey) || (event.shiftKey)) {
        alert('키를 사용할 수 없습니다.');
    }
}
document.onmousedown = click;
document.onkeydown = click;

오늘 하루 이 창을 열지 않음

<html>
<head>
<title>오늘 하루 이 창을 열지 않음</title>
<script type="text/javascript">
function setCookie( name, value, expiredays ) {
    var todayDate = new Date();
        todayDate.setDate( todayDate.getDate() + expiredays );
        document.cookie = name + "=" + escape( value ) + "; path=/; expires=" + todayDate.toGMTString() + ";"
    }

function closeWin() {
    if ( document.notice_form.chkbox.checked ){
        setCookie( "maindiv", "done" , 1 );
    }
    document.all['divpop'].style.visibility = "hidden";
}
</script>
</head>

<body bgcolor="#FFFFFF" text="#000000" leftmargin="0" topmargin="0" marginwidth="0" marginheight="0">  
<div id="divpop" style="position:absolute;left:395px;top:190;z-index:200;visibility:hidden;">
<table width=300 height=400 cellpadding=2 cellspacing=0>
<tr>
    <td style="border:1px #666666 solid" height=360 align=center bgcolor=white>여기에 내용 삽입</td>
</tr>
<tr>
    <td align=right bgcolor=white>
        <form name="notice_form">
            <input type="checkbox" name="chkbox" value="checkbox">오늘 하루 이 창을 열지 않음
            <a href="javascript:closeWin();"><B>[닫기]</B></a>
        </form>
    </td>
</tr>
</table>
</div>  

<script type="text/javascript">
cookiedata = document.cookie;    
if ( cookiedata.indexOf("maindiv=done") < 0 ){      
   document.all['divpop'].style.visibility = "visible";
   }
   else {
       document.all['divpop'].style.visibility = "hidden";
}
</script>
</body>
</html>

숫자 천단위 콤마 찍기

var s = commify(-1234567890.123);
document.write(s + '<br />');
// 출력 결과: -1,234,567,890.123


function commify(n) {
  var reg = /(^[+-]?\d+)(\d{3})/;   // 정규식
  n += '';                          // 숫자를 문자열로 변환

  while (reg.test(n))
    n = n.replace(reg, '$1' + ',' + '$2');

  return n;
}

replaceAll 구현

자바스크립트는 replace() 함수 사용 시 한번만 치환된다.

var a = "2008-08-28";
var b = a.replace("-","");
alert(b);    // 200808-28

아래와 같이 split 함수와 join 함수를 쓰면 이러한 문제가 해결 된다.

var a = "2008-08-28";
var b = a.split("-").join("");
alert(b);    // 20080828


댓글목록

등록된 댓글이 없습니다.

전체 142
게시물 검색
jQuery 목록
번호 제목 글쓴이 조회 날짜
62 no_profile 오원장 쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 4036 11-29
61 no_profile 오원장 쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 6588 09-17
60 no_profile 오원장 쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 5455 08-21
59 no_profile 오원장 쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 4826 08-21
58 no_profile 오원장 쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 6394 07-13
57 no_profile 오원장 쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 5952 06-13
56 no_profile 오원장 쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 5282 04-28
55 no_profile 오원장 쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 5460 04-24
54 no_profile 오원장 쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 4836 04-24
53 no_profile 오원장 쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 5741 04-24
52 no_profile 오원장 쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 4788 04-24
51 no_profile 오원장 쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 4375 04-20
50 no_profile 오원장 쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 4002 04-19
49 no_profile 오원장 쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 4363 04-19
48 no_profile 오원장 쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 4009 04-17
47 no_profile 오원장 쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 4324 04-11
46 no_profile 오원장 쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 4383 04-01
열람중 no_profile 오원장 쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 4550 04-01
44 no_profile 오원장 쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 4253 03-31
43 no_profile 오원장 쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 4319 03-22