<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>제목 없음</title>
    <style type="text/css">
        div.fileinputs {
 position: relative;
}

div.fakefile {
 position: absolute;
 top: 0px;
 left: 0px;
 z-index: 1;
}

input.file {
 position: relative;
 text-align: right;
 -moz-opacity:0 ;
 filter:alpha(opacity: 0);
 opacity: 0;
 z-index: 2;
}

    </style>
    <script language="javascript">
        var W3CDOM = (document.createElement && document.getElementsByTagName);

function initFileUploads() {
 if (!W3CDOM) return;
 var fakeFileUpload = document.createElement('div');
 fakeFileUpload.className = 'fakefile';
 fakeFileUpload.appendChild(document.createElement('input'));
 var image = document.createElement('img');
 image.src='pix/button_select.gif';
 fakeFileUpload.appendChild(image);
 var x = document.getElementsByTagName('input');
 for (var i=0;i<x.length;i++) {
  if (x[i].type != 'file') continue;
  if (x[i].parentNode.className != 'fileinputs') continue;
  x[i].className = 'file hidden';
  var clone = fakeFileUpload.cloneNode(true);
  x[i].parentNode.appendChild(clone);
  x[i].relatedElement = clone.getElementsByTagName('input')[0];
  x[i].onchange = x[i].onmouseout = function () {
   this.relatedElement.value = this.value;
  }
 }
}

    </script>
</head>
<body>   
    <div class="fileinputs">
     <input type="file" class="file" />
     <div class="fakefile">
      <input />
      <img src="images/btnImgSearch.gif" />
     </div>
    </div>

</body>
</html>

출처 : 아마도 www.quirksmode.org -ㅗ-);

Posted by zany2974
,

<table cellpadding="0" cellspacing="0" summary="테이블 정보">
 <caption>테이블 타이틀, 목적</caption>

<colgroup>
<col  />
<col  />
<col  />
</colgroup>

    <thead>
      <tr>
         <th scope="col" abbr="테이블관련">테이블 관련1</th>
         <th scope="col" abbr="테이블관련">테이블 관련2</th>
         <th scope="col" abbr="테이블관련">테이블 관련3</th>
      </tr>
   </thead>
    <tbody>
      <tr>
         <td scope="row">테이블 관련1-1번 내용</td>
         <td>테이블 관련1-2번 내용</td>
         <td>테이블 관련1-3번 내용</td>
      </tr>
   </tbody>
    <tfoot>
      <tr>
         <td scope="row">테이블 관련1-4번 내용</td>
         <td>테이블 관련1-5번 내용</td>
         <td>테이블 관련1-6번 내용</td>
      </tr>
   </tfoot>
</table>


thead, tbody, tfoot

여러개의 행을 하나의 그룹으로 묶어주는 엘리먼트 입니다.
테이블 안에서 이 3개의 태그는 사용이 제한이 있는데 thead와 tfoot는 한 테이블에서 하나만 작성을 할 수가 있습니다. 하지만 tbody의 경우는 여러번 사용해도 무방합니다.

header 의th 태그를 적용하면 글자가 bold체로 굵게 표시되고 가운데 정렬을 하게 됩니다.

summary

표의 목적이나, 음성, 점자등 보이지 않는 메디아 표현의 구조를 제공합니다.
해당 테이블의 내용이 뭔지를 축약적으로 나타낼 수 있습니다. 이미지 태그의 alt 속성과 같다고 할 수 있습니다.

caption 

** 닫는 태그 필요

테이블의 열이나 행 앞에 header나 caption을 넣어 줄때 사용합니다.
caption태그는 반드시 table태그 블록에 포함 되어야 합니다.
default 정렬방식은 중앙정렬 입니다.

▶ 속성

① align = top | left | right | bottom
              top : 행의 상단에 배치
              left : 문자열을 왼쪽에 정렬
              right : 문자열을 오른쪽에 정렬
              bottom : 행의 하단에 배치

② class : css의 class 선택자를 지정합니다.

③ id : css의 id 선택자를 지정합니다

④ style : css스타일을 지정합니다.

colgroup  

** 닫는 태그 선택적

표의 세로줄 그룹을 만들때 사용합니다. table요소내에서 caption뒤 thead 앞에 위치 해야 합니다.

▶ 속성

① class : css의 class 선택자를 지정 합니다.

② id : css의 id 선택자를 지정합니다.

③ style : css 스타일을 지정합니다.
             (적용할 수 있는 스타일은 border, background, width 입니다.)

④ span : 그룹화할 세로줄의 개수를 지정합니다.

⑤ width : 세로줄 그룹의 너비를 지정합니다.

⑥  align = top | left | right | bottom | center 
               (ie에서만 적용됩니다. 구글이나 파이어폭스에서 적용안됨)

col

** 닫는 태그 없음

표의 세로줄을 지정할때 사용합니다. table요소내에서 caption뒤 thead 앞에 위치 해야 합니다.
colgroup과 달리 col은 세로줄을 구조적으로 그룹핑하지 않으며 단순히 하나 이상 세로줄에 공통적인 속성을
정의 합니다.
col요소는 table요소 안에 바로 포함되거나 colgroup 안에 포함될 수 있습니다.
col요소가 colgroup안에 있을때 col속성은 colgroup속성보다 우선합니다.

▶ 속성

① class : css의 class 선택자를 지정 합니다.

② id : css의 id 선택자를 지정합니다.

③ style : css 스타일을 지정합니다.
              (적용할 수 있는 스타일은 border, background, width 입니다.)
  
④ width : 디폴트 값은 픽셀입니다. %로도 사용이 가능합니다.

     구문 : <col width="10" />,  <col width="10%" />


⑤ span : 그룹화할 가로줄의 개수를 지정합니다.

scope

데이터의 header 정보를 제공합니다.

col : 그 열의 header의 정보를 제공합니다.
row : 그 행의 header의 정보를 제공합니다.

위의 테이블에서 보시다시피 겉으로는 scope 속성이 적용되었는지 알 수 없습니다.
하지만 scope속성을 적용함으로써
'테이블 관련1' 에 해당하는 데이터는 '테이블관련1-1번내용', '테이블관련1-4번내용' 이고
'테이블관련 1-1' 에 해당하는 데이터는 '테이블관련1-2번내용', '테이블관련1-3번내용'이라는
정보를 브라우저에게 알려주게 되는 것입니다.

abbr (헤더의 요약)

스크린리더가 테이블의 내용을 읽어 내려갈때 테이블의 내용(td) 보다는 상단header(th)부분부터 읽게 될 것입
니다. 만약 이때 헤더(th) 내용이 길게 들어가면 스크린리더가 행을 읽을때마다 헤더의 내용을 계속 반복해서
읽게 될 것입니다.
abbr속성은 이렇게 길게 들어가 있는 헤더의 내용을 단축해서 표현해주는 역활을 합니다.

 

 

출처 : http://yumtang.tistory.com/14

Posted by zany2974
,

정규식

Javascript 2011. 1. 18. 08:37

*본 페이지에는 자바스크립트가 많이 들어있습니다. 자바스크립트가 실행되지 않으면 제대로 보이지 않습니다.
*본 페이지는 IE용 태그를 사용하였으므로, firefox 등에서는 정상작동하지 않을 수 있습니다.

차례

1. 정규식이란?

  • String의 검색,치환,추출을 위한 패턴.
  • 언어별 사용법은 대동소이함.
  • 패턴예>전화번호 형식, 이메일 형식 등.

2. 정규식 만들기

  1. Javascript
    • var regexp = /pattern/[flags] ;
      var test = regexp.test(to be checked)
    • var regexp = new RegExp("pattern"[, "flags"]);
      var test = regexp.test(to be checked)
    • flags for javascript
      • g : global match, 일반적으로 패턴이 1번만 발견되면 찾기를 종료하지만, g flag가 있으면, 문자열 내에서 모든 패턴을 찾는다.
      • i : ignore case, 대소문자를 고려하지 않고 체크한다.[a-z]와 [A-Z]는 같은 표현이 된다.
      • m : match over multiple lines, 여러 줄에 걸쳐 체크를 한다.
  2. Java
    • java.util.regex package
    • Pattern p = Pattern.compile("pattern");
      Matcher m = p.matcher("string to be checked");
      boolean b = m.matches();
    • boolean b = Pattern.matches("pattern", "string to be checked");

3. 정규식 표현법

*는 valid, 는 invalid
*두꺼운 글씨체는 매칭되는 부분.
*예제는 javascript 기준이며, 언어에 따라 다소 차이가 발생할 수 있다.
문자 용도 예제
\
  • 특수문자를 의미
  • 특수문자의 사용을 제외(특수문자 앞에서)
  • b는 b라는 글자를 의미 하지만 \b는 단어 경계를 의미
  • *은 0번이상 반복이라는 의미이지만, \*는 *이라는 글자를 의미.
^ 문자열의 시작. []안에서는 not의 의미
* ^A는 "A로 시작"이라기 보다는 "시작 직후에 A가 나온다"는 의미로 해석하는 것이 좋다. 즉, 시작과 끝과 같은 빈 공간을 하나의 문자로 간주하는 것이 좋다.
/^A/g
  • A string
  • an A
/[^A]/g
  • A string
  • an A
/^A/g
  • A string
  • an A
/[^A]/g
  • A string
  • an A
$ 문자열의 마지막
/t$/
  • eat
  • GREAT
/t$/
  • eat
  • GREAT
* 0번 이상 반복 /ab*d/g
  • ad
  • abd
  • abdcdeabbbbdedb
  • ab
  • axd
/ab*d/g
  • ad
  • abd
  • abdcdeabbbbdedb
  • ab
  • axd
+ 1번 이상 반복 ( = {1,} ) /ab+d/g
  • ad
  • abd
  • abdcdeabbbbdedb
  • ab
  • axd
/ab+d/g
  • ad
  • abd
  • abdcdeabbbbdedb
  • ab
  • axd
? 0번 이나 1번 /e?le?/g
  • angel
  • angle
  • element
/abc\-?d/g
  • abc-d
  • abcd
/e?le?/g
  • angel
  • angle
  • element
/abc\-?d/g
  • abc-d
  • abcd
. new line 을 제외한 모든 글자 /.n/g
  • nay, an apple is on the tree
  • nay
/.n/g
  • nay, an apple is on the tree
  • nay
(x) x를 체크하고 체크한 값을 변수로 저장 /(f..) (b..)/
  • foo bar
    1th :foo
    2th :bar
/(f..) (b..)/
  • foo bar
    1th :foo
    2th :bar
(?:x) x를 체크하고 체크한 값을 변수로 저장하지 않음 /(?:f..) (b..)/
  • foo bar
    1th :bar
  • bar foo
/(?:f..) (b..)/
  • foo bar
    1th :bar
  • bar foo
x|y x 또는 y /green|red/
  • green apple
  • red apple
  • yellow apple
/green|red/
  • green apple
  • red apple
  • yellow apple
x(?=y) x후에 y가 나오고, x부분만 매칭되는 부분으로 간주 /Tmax(?=soft|hard)/
  • Tmaxsoft
  • Tmaxhard
  • Tmax soft
/Tmax(?=soft).*/
  • Tmaxsoft
  • Tmaxhard
  • Tmax soft
/Tmax(?=soft|hard)/
  • Tmaxsoft
  • Tmaxhard
  • Tmax soft
/Tmax(?=soft).*/
  • Tmaxsoft
  • Tmaxhard
  • Tmax soft
x(?!y) x가 나오고 그 뒤에 y가 있으면 안 됨 /Tmax(?!hard)/
  • Tmaxsoft
  • Tmaxhard
  • Tmax soft
/Tmax(?!hard)/
  • Tmaxsoft
  • Tmaxhard
  • Tmax soft
{n} 앞에 지정한 것이 n개 /.{3}/
  • ab
  • abc
  • abcd
  • 홍길동
/.{3}/
  • ab
  • abc
  • abcd
  • 홍길동
{n,} 앞에 지정한 것이 n개 이상 /.{3,}/
  • ab
  • abc
  • abcd
/.{3,}/
  • ab
  • abc
  • abcd
{n,m} 앞에 지정한 것이 n~m개 /.{3,5}/
  • ab
  • abc
  • abcd
  • 홍길동
/.{3,5}/
  • ab
  • abc
  • abcd
  • 홍길동
[xyz] x나 y나 z. []안에는 얼마든지 쓸 수 있다. /[abc]{2}/
  • ab
  • abc
  • adbd
/[abc]{2}/
  • ab
  • abc
  • adbd
[x-z] x에서 z까지 /[a-z]{4,}/g
  • She sells sea shells by the sea shore는 Very 어렵다!
/[a-z]{4,}/g
  • She sells sea shells by the sea shore는 Very 어렵다!
[^xyz] x,y,z를 제외한 나머지 모든 것 /[^a-z]{2,}/g
  • I'm a good man
  • I am A good Man
/[^a-z]{2,}/g
  • I'm a good man
  • I am A good Man
[\b] 백스페이스. \b와 혼동하지 말것. /[\b]/g
  • abcd
/[\b]/g
  • abcd
일반적인 String에서는 \b가 백스페이스를 의미한다.
\b 단어의 경계.[\b]와 혼동하지 말것. /\bn[a-z]/g
  • I am not a boy
  • online
  • nope
/\bn[a-z]/g
  • I am not a boy
  • online
  • nope
\B \b 를 제외한 전부 /\Bn[a-z]/g
  • noonday
  • online
  • nope
/\Bn[a-z]/g
  • noonday
  • online
  • nope
\cX 컨트롤X와 매칭. \cM은 컨트롤M과 매칭
\d 숫자.[0-9]와 같음 /\d/g
  • 7 eight 9
  • 123
/^0[0-9]{2}/g
  • 0120
  • 12011
/\d/g
  • 7 eight 9
  • 123
/^0[0-9]{2}/g
  • 0120
  • 12011
\D \d 를 제외한 전부 /\D/g
  • 7 eight 9
  • 12?3
/\D/g
  • 7 eight 9
  • 12?3
\f form-feed
\n new line
\r carriage return
\s white space
ex>탭, 띄어쓰기, \n, \r
/k\s/g
  • korea
  • blank is
  • blank
/k\s/g
  • korea
  • blank is
  • blank
\S \s 를 제외한 전부 /k\S/g
  • korea
  • blank is
/k\S/g
  • korea
  • blank is
\t
\v vertical tab
\w 알파벳+숫자+_. [A-Za-z0-9_]와 동일 /\w/g
  • !@#$%^&*()+_-[]{}\|"':;,.<>?/
/\w/g
  • !@#$%^&*()+_-[]{}\|"':;,.<>?/
        _가 <b>를 먹여도 별로 티가 안 난다.
\W \w 빼고 전부 /\W/g
  • !@#$%^&*()+_-[]{}\|"':;,.<>?/
/\W/g
  • !@#$%^&*()+_-[]{}\|"':;,.<>?/
\n \n이 자연수일때, ()로 지정한 n번째 정규식 /(.{2})e tru\1 is \1at/
  • the truth is that ...
    1th :th
/(.{2})e tru\1 is \1at/
  • the truth is that ...
    1th :th
(th)가 \1로 지정된다.
\xhh hh는 hexacode, /[\x21-\x40]/g
  • !@#$%^&*()po
/[\x21-\x40]/g
  • !@#$%^&*()po
Code table 보기
\uhhhh hhhh는 hexacode, /[\u3131-\u3163\uac00-\ud7a3]/g
  • Tmax .
/[\u3131-\u3163\uac00-\ud7a3]/g
  • Tmax .
코드 번호> 3131:ㄱ 3163:ㅣ ac00:가 d7a3:힣 (javascript, java)

4. 정규식 사용 예제

/^[0-9]/
  • 09없다
  • 100점
  • 집이 10평
/^[0-9]/
  • 09없다
  • 100점
  • 집이 10평
/^\w+$/
  • tmaxsoft
  • tmax(co)
  • tmax soft
/^\w+$/
  • tmaxsoft
  • tmax(co)
  • tmax soft
/^[a-zA-Z][\w\-]{4,11}$/
  • tmax2010
  • tmax-2010!
  • 2010tmax
  • ILikegoooooooooooooooooogle
/^[a-zA-Z][\w\-]{4,11}$/
  • tmax2010
  • tmax-2010!
  • 2010tmax
  • ILikegoooooooooooooooooogle
/^[0-9]{2,3}-[0-9]{3,4}-[0-9]{4}/
  • 02-6288-2114
  • 031-779-7114
  • 12-1234-5678
  • 02-6288-2114545
  • 02-0288-2114
/^[0-9]{2,3}-[0-9]{3,4}-[0-9]{4}/
  • 02-6288-2114
  • 031-779-7114
  • 12-1234-5678
  • 02-6288-2114545
  • 02-0288-2114
/^0\d{1,2}-[1-9]\d{2,3}-\d{4}$/
  • 02-6288-2114
  • 031-779-7114
  • 12-1234-5678
  • 02-2123-12314545
  • 02-0288-2114
/^0\d{1,2}-[1-9]\d{2,3}-\d{4}$/
  • 02-6288-2114
  • 031-779-7114
  • 12-1234-5678
  • 02-2123-12314545
  • 02-0288-2114
/^[\.a-zA-Z0-9\-]+\.[a-zA-Z]{2,}/
  • r-d.tmax.co.kr
  • r-d.tmax.co.kr입니다.
  • tmax..co.kr
  • a.com
/^[\.a-zA-Z0-9\-]+\.[a-zA-Z]{2,}/
  • r-d.tmax.co.kr
  • r-d.tmax.co.kr입니다.
  • tmax..co.kr
  • a.com
/^(?:[\w\-]{2,}\.)+[a-zA-Z]{2,}$/
  • r-d.tmax.co.kr
  • r-d.tmax.co.kr입니다.
  • tmax..co.kr
  • a.com
/^(?:[\w\-]{2,}\.)+[a-zA-Z]{2,}$/
  • r-d.tmax.co.kr
  • r-d.tmax.co.kr입니다.
  • tmax..co.kr
  • a.com
/^[_a-zA-Z0-9\-]+@[\._a-zA-Z0-9\-]+\.[a-zA-Z]{2,}/
  • hwangjc@tmax.co.kr
  • hwangjc@tmax..co.kr
  • hwang@a.com
/^[_a-zA-Z0-9\-]+@[\._a-zA-Z0-9\-]+\.[a-zA-Z]{2,}/
  • hwangjc@tmax.co.kr
  • hwangjc@tmax..co.kr
  • hwang@a.com
/^[\w\-]+@(?:(?:[\w\-]{2,}\.)+[a-zA-Z]{2,})$/
  • hwangjc@tmax.co.kr
  • hwangjc@tmax..co.kr
  • hwang@a.com
/^[\w\-]+@(?:(?:[\w\-]{2,}\.)+[a-zA-Z]{2,})$/
  • hwangjc@tmax.co.kr
  • hwangjc@tmax..co.kr
  • hwang@a.com
/^([a-z]+):\/\/((?:[a-z\d\-]{2,}\.)+[a-z]{2,})(:\d{1,5})?(\/[^\?]*)?(\?.+)?$/i
  • http://www.tmax.co.kr/main/index.jsp?var=value
    1th :http
    2th :www.tmax.co.kr
    3th :
    4th :/main/index.jsp
    5th :?var=value
  • http://www.tmax.co.kr/main/index.jsp
    1th :http
    2th :www.tmax.co.kr
    3th :
    4th :/main/index.jsp
    5th :
  • http://tmax.co.kr/
    1th :http
    2th :tmax.co.kr
    3th :
    4th :/
    5th :
  • http://tmax.co.kr
    1th :http
    2th :tmax.co.kr
    3th :
    4th :
    5th :
  • http://tmax.co.kr:8088/main/
    1th :http
    2th :tmax.co.kr
    3th ::8088
    4th :/main/
    5th :
/^([a-z]+):\/\/((?:[a-z\d\-]{2,}\.)+[a-z]{2,})(:\d{1,5})?(\/[^\?]*)?(\?.+)?$/i
  • http://www.tmax.co.kr/main/index.jsp?var=value
    1th :http
    2th :www.tmax.co.kr
    3th :
    4th :/main/index.jsp
    5th :?var=value
  • http://www.tmax.co.kr/main/index.jsp
    1th :http
    2th :www.tmax.co.kr
    3th :
    4th :/main/index.jsp
    5th :
  • http://tmax.co.kr/
    1th :http
    2th :tmax.co.kr
    3th :
    4th :/
    5th :
  • http://tmax.co.kr
    1th :http
    2th :tmax.co.kr
    3th :
    4th :
    5th :
  • http://tmax.co.kr:8088/main/
    1th :http
    2th :tmax.co.kr
    3th ::8088
    4th :/main/
    5th :
/^[ㄱ-ㅣ가-힣]+$/
  • 티맥스소프트
  • ㅜㅜ
  • ㅎㅎ
/^[ㄱ-ㅣ가-힣]+$/
  • 티맥스소프트
  • ㅜㅜ
  • ㅎㅎ

5. Javascript 정규식 함수

함수 코드예제 코드설명
Array RegExp.exec (to be checked)
var myRe=/d(b+)(d)/ig;
var myArray = myRe.exec("cdbBdbsbz");

/d(b+)(d)/ig

  • cdbBdbsbz
/d(b+)(d)/ig
  • cdbBdbsbz
myArray.index ="1" ; (처음으로 매칭되는 위치, 컴터가 늘 그렇듯 위치는 0번째부터 센다.)
myArray.input ="cdbBdbsbz;" (체크할 대상)
myArray[0] ="dbBd;(검사에" 통과한 부분)
myArray[1] ="bB;(1번째" 괄호에서 체크된 부분)
myArray[2] ="d;(2번째" 괄호에서 체크된 부분)

myRe.lastIndex ="5" ; (다음번 체크를 하기위한 위치.)
myRe.ignoreCase ="true;" (/i 플래그 체크)
myRe.global ="true;" (/g 플래그 체크)
myRe.multiline ="false;" (/m 플래그 체크)

RegExp.$_ ="cdbBdbsbz;(입력한" 스트링)
RegExp.$1 ="bB;(1번째" 괄호에서 체크된 부분 )
boolean RegExp.test(to be checked)
var myRe=/d(b+)(d)/ig;
var checked = myRe.test("cdbBdbsbz");
document.write("checked = " + checked +";<br>");

/d(b+)(d)/ig

  • cdbBdbsbz
/d(b+)(d)/ig
  • cdbBdbsbz
실행결과: checked = true;
String RegExp.toString()
var myRe=/d(b+)(d)/ig;
var str = myRe.toString();
document.write(str);
<span id="callbacknestaesop0825tistorycom92236" style="width:1px; height:1px; float:right"><embed  allowscriptaccess="always"  id="bootstrapperaesop0825tistorycom92236"  src="http://aesop0825.tistory.com/plugin/CallBack_bootstrapperSrc"  width="1"  height="1"  wmode="transparent"  type="application/x-shockwave-flash"  EnableContextMenu="false"  FlashVars="&callbackId=aesop0825tistorycom92236&host=http://aesop0825.tistory.com&embedCodeSrc=http%3A%2F%2Faesop0825.tistory.com%2Fplugin%2FCallBack_bootstrapper%3F%26src%3Dhttp%3A%2F%2Fcfs.tistory.com%2Fblog%2Fplugins%2FCallBack%2Fcallback%26id%3D9%26callbackId%3Daesop0825tistorycom92236%26destDocId%3Dcallbacknestaesop0825tistorycom92236%26host%3Dhttp%3A%2F%2Faesop0825.tistory.com%26float%3Dleft" swLiveConnect="true"/></span>
실행 결과:
String String.replace(pattern or string, to be replaced)
var str = "abcdefe";
document.write(str.replace("e" , "f"));
실행 결과: abcdffe

e가 2번 있지만, 첫번째 인자가 정규식이 아니라 문자열일 경우는 첫번째 것만 바꾼다.
var str = "aba";
document.write(str.replace(/^a/ , "c"));
실행 결과: cba
var re = /(\w+)\s(\w+)/;
var str = "John Smith";
newstr = str.replace(re, "$2, $1");
document.write(newstr)
실행 결과: Smith, John

re에 의해서 찾아진 문자열 들은 re에서 ()로 표현된 순서대로 $1, $2와 같이 변수로 저장된다.
var re = /\s(?:http|https):\/\/\S*(?:\s|$)/g;
var str = "url is http://iilii.egloos.com/ !!\n";
str += "tmax home: http://www.tmax.co.kr";
newstr = str.replace(re, function (str,p1,offset,s) {
     return "<a href='" + str + "'>" + str + "</a>";
  }
).replace(/\n/, "<br>");
document.write(newstr);
url is http://iilii.egloos.com/ !!
tmax home: http://www.tmax.co.kr

str: 찾은 문자열
p1: ()에서 검색된 1번째 문자열. 마찬가지로 p2,p3 등도 가능
offset: str을 찾은 위치
s : 원본 문자열.
Array String.match(regular expression
var str = "ABCdEFgHiJKL";
var myResult = str.match(/[a-z]/g );
for(var cnt = 0 ; cnt < myResult.length; cnt++){
    document.write(cnt +":" + myResult[cnt] +"<br>");
}

document.write("비교<br>");

var str = "ABCdEFgHiJKL";
var myResult = /[a-z]/g.exec(str);
for(var cnt = 0 ; cnt < myResult.length; cnt++){
    document.write(cnt +":" + myResult[cnt] +"<br>");
}
실행 결과:
0:d
1:g
2:i
비교
0:d

String.match(RegExp) =>g flag가 있어도 다 찾아낸다.
RegExp.exec(String) =>g flag가 있으면, 한 개만 찾고 끝낸다.
Array String.split([separator[, limit]])
var str = "ABCdEFgHiJKL";
var myResult = str.split(/[a-z]/g , 3);
for(var cnt = 0 ; cnt < myResult.length; cnt++){
    document.write(cnt +":" + myResult[cnt] +"<br>");
}
실행 결과:
0:ABC
1:EF
2:H

주어진 문자열을 separator를 기준으로 limit 만큼 자른다.

6. 정규식으로 만든 유용한 Javascript 함수

String removeTags(input)

HTML tag부분을 없애준다
function removeTags(input) {
    return input.replace(/<[^>]+>/g, ""); 
};
example>
var str = "<b>Tmax</b> <i>soft</i>";
document.write(str +"<br>");
document.write(removeTags(str));
result>
Tmax soft
Tmax soft

String String.trim()

문자열의 앞뒤 공백을 없애준다.
String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, ''); 
};
example>
var str = "         untrimed string            ";
document.write("========" + str+ "==============<br>");
document.write("========" + str.trim() + "==============");
result>
======== untrimed string ==============
========untrimed string==============

String String.capitalize()

단어의 첫 글자를 대문자로 바꿔준다.
String.prototype.capitalize = function() {
    return this.replace(/\b([a-z])/g, function($1){
        return $1.toUpperCase();
    }) ;  
};
example>
var str = "korea first world best";
document.write(str.capitalize());
result>
Korea First World Best

String number_format(input)

입력된 숫자를 ,를 찍은 형태로 돌려준다
function number_format(input){
    var input = String(input);
    var reg = /(\-?\d+)(\d{3})($|\.\d+)/;
    if(reg.test(input)){
        return input.replace(reg, function(str, p1,p2,p3){
                return number_format(p1) + "," + p2 + "" + p3;
            }    
        );
    }else{
        return input;
    }
}
example>
document.write(number_format(1234562.12) + "<br>");
document.write(number_format("-9876543.21987")+ "<br>");
document.write(number_format("-123456789.12")+ "<br>");
result>
1,234,562.12
-9,876,543.21987
-123,456,789.12

7. Java 정규식 함수

Pattern p = Pattern.compile("(a*)(b)");
Matcher m = p.matcher("aaaaab");
if (m.matches()) {
    for (int i = 0; i < m.groupCount() + 1; i++) {
        System.out.println(i + ":" + m.group(i));
    }
} else {
    System.out.println("not match!");
}

result>
0:aaaaab
1:aaaaa
2:b
0번째는 매칭된 부분.
String a = "I love her";
System.out.println(a.replaceAll("([A-Z])", "\"$1\""));

result>
"I" love her
자바도 $1을 쓸 수 있다.
Pattern p = Pattern.compile("cat");
Matcher m = p.matcher("one cat two cats in the yard");
StringBuffer sb = new StringBuffer();
while (m.find()) {
    m.appendReplacement(sb, "dog");
    System.out.println(sb.toString());
}
m.appendTail(sb);
System.out.println(sb.toString());

result>
one dog
one dog two dog
one dog two dogs in the yard
Posted by zany2974
,