정규식 정규식 정리

황제낙엽 2008.11.24 10:46 조회 수 : 252 추천:104

sitelink1  
sitelink2  
sitelink3  
sitelink4  
extra_vars4  
extra_vars5  
extra_vars6  
http://kio.zc.bz/Lecture/regexp.html
본 문서의 저작권은 anti-nhn license에 따릅니다.
*본 페이지에는 자바스크립트가 많이 들어있습니다. 자바스크립트가 실행되지 않으면 제대로 보이지 않습니다.
*본 페이지는 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
$문자열의 마지막
/t$/
  • eat
  • GREAT
*0번 이상 반복/ab*d/g
  • ad
  • abd
  • abdcdeabbbbdedb
  • ab
  • axd
+1번 이상 반복 ( = {1,} )/ab+d/g
  • ad
  • abd
  • abdcdeabbbbdedb
  • ab
  • axd
?0번 이나 1번/e?le?/g
  • angel
  • angle
  • element
/abc-?d/g
  • abc-d
  • abcd
.new line 을 제외한 모든 글자/.n/g
  • nay, an apple is on the tree
  • nay
(x)x를 체크하고 체크한 값을 변수로 저장/(f..) (b..)/
  • foo bar
    1th :foo
    2th :bar
(?:x)x를 체크하고 체크한 값을 변수로 저장하지 않음/(?:f..) (b..)/
  • foo bar
    1th :bar
  • bar foo
x|yx 또는 y/green|red/
  • green apple
  • red apple
  • yellow apple
x(?=y)x후에 y가 나오고, x부분만 매칭되는 부분으로 간주/blah(?=soft|hard)/
  • blahsoft
  • blahhard
  • blah soft
/blah(?=soft).*/
  • blahsoft
  • blahhard
  • blah soft
x(?!y)x가 나오고 그 뒤에 y가 있으면 안 됨/blah(?!hard)/
  • blahsoft
  • blahhard
  • blah soft
{n}앞에 지정한 것이 n개/.{3}/
  • ab
  • abc
  • abcd
  • 홍길동
{n,}앞에 지정한 것이 n개 이상/.{3,}/
  • ab
  • abc
  • abcd
{n,m}앞에 지정한 것이 n~m개/.{3,5}/
  • ab
  • abc
  • abcd
  • 홍길동
[xyz]x나 y나 z. []안에는 얼마든지 쓸 수 있다./[abc]{2}/
  • ab
  • abc
  • adbd
[x-z]x에서 z까지/[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
[b]백스페이스. b와 혼동하지 말것./[b]/g
  • abcd
일반적인 String에서는 b가 백스페이스를 의미한다.
b단어의 경계.[b]와 혼동하지 말것./bn[a-z]/g
  • I am not a boy
  • online
  • nope
Bb 를 제외한 전부/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
Dd 를 제외한 전부/D/g
  • 7 eight 9
  • 12?3
fform-feed
nnew line
rcarriage return
swhite space
ex>탭, 띄어쓰기, n, r
/ks/g
  • korea
  • blank is
  • blank
Ss 를 제외한 전부/kS/g
  • korea
  • blank is
t
vvertical tab
w알파벳+숫자+_. [A-Za-z0-9_]와 동일/w/g
  • !@#$%^&*()+_-[]{}|"':;,.<>?/
        _가 <b>를 먹여도 별로 티가 안 난다.
Ww 빼고 전부/W/g
  • !@#$%^&*()+_-[]{}|"':;,.<>?/
nn이 자연수일때, ()로 지정한 n번째 정규식/(.{2})e tru1 is 1at/
  • the truth is that ...
    1th :th
(th)가 1로 지정된다.
xhhhh는 hexacode, /[x21-x40]/g
  • !@#$%^&*()po
Code table 보기
uhhhhhhhh는 hexacode, /[u3131-u3163uac00-ud7a3]/g
  • blah .
코드 번호> 3131:ㄱ 3163:ㅣ ac00:가 d7a3:힣 (javascript, java)

4. 정규식 사용 예제

/^[0-9]/
  • 09없다
  • 100점
  • 집이 10평
/^w+$/
  • blahsoft
  • blah(co)
  • blah soft
/^[a-zA-Z][w-]{4,11}$/
  • blah2010
  • blah-2010!
  • 2010blah
  • 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
/^0d{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.blah.co.kr
  • r-d.blah.co.kr입니다.
  • blah..co.kr
  • a.com
/^(?:[w-]{2,}.)+[a-zA-Z]{2,}$/
  • r-d.blah.co.kr
  • r-d.blah.co.kr입니다.
  • blah..co.kr
  • a.com
/^[_a-zA-Z0-9-]+@[._a-zA-Z0-9-]+.[a-zA-Z]{2,}/
  • abc@haha.co.kr
  • abc@haha..co.kr
  • hwang@a.com
/^[w-]+@(?:(?:[w-]{2,}.)+[a-zA-Z]{2,})$/
  • abc@haha.co.kr
  • abc@haha..co.kr
  • hwang@a.com
/^([a-z]+)://((?:[a-zd-]{2,}.)+[a-z]{2,})(:d{1,5})?(/[^?]*)?(?.+)?$/i
  • http://www.blah.co.kr/main/index.jsp?var=value
    1th :http
    2th :www.blah.co.kr
    3th :
    4th :/main/index.jsp
    5th :?var=value
  • http://www.blah.co.kr/main/index.jsp
    1th :http
    2th :www.blah.co.kr
    3th :
    4th :/main/index.jsp
    5th :
  • http://blah.co.kr/
    1th :http
    2th :blah.co.kr
    3th :
    4th :/
    5th :
  • http://blah.co.kr
    1th :http
    2th :blah.co.kr
    3th :
    4th :
    5th :
  • http://blah.co.kr:8088/main/
    1th :http
    2th :blah.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
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
실행결과: checked = true;
String RegExp.toString()
var myRe=/d(b+)(d)/ig;
var str = myRe.toString();
document.write(str);

 

실행 결과: /d(b+)(d)/ig
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 += "blah home: http://www.blah.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/ !!
blah home: http://www.blah.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>blah</b> <i>soft</i>";
document.write(str +"<br>");
document.write(removeTags(str));
result>
blah soft
blah 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:aaaaab1:aaaaa2:b0번째는 매칭된 부분.
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 dogone dog two dogone dog two dogs in the yard

번호 제목 글쓴이 날짜 조회 수
77 [펌] 아사페릴의 사생활 - __proto__ 와 construct 와 prototype 황제낙엽 2009.04.02 23
76 [펌] 아사페릴의 사생활 - prototype과 __proto__ 와 constructor 황제낙엽 2009.04.02 41
75 [펌] 아사페릴의 사생활 - __proto__ 와 prototype에 대해.. 황제낙엽 2009.04.02 15
74 [펌] 아사페릴의 사생활 - Javascript의 클래스에 관한 이야기 황제낙엽 2009.04.02 17
73 [펌] 아사페릴의 사생활 - Javascript의 constructor 와 prototype 황제낙엽 2009.04.02 156
72 [펌] prototype (2) 황제낙엽 2009.04.02 9
71 [펌] prototype (1) 황제낙엽 2009.04.02 12
70 unshift() Method 황제낙엽 2009.03.02 287
69 javascript replaceall의 방법에 따른 처리 속도 비교 황제낙엽 2009.02.11 97
68 파이어폭스로 스크립트 디버깅하기 황제낙엽 2009.01.14 22
67 숫자 여부와 자리수를 체크 하는 예제 황제낙엽 2009.01.12 5265
66 익스플로러용 스크립트 디버거 (Script Debugger for Windows NT 4.0 and Later) 황제낙엽 2008.12.11 176
65 소숫점을 포함한 반올림 황제낙엽 2008.12.11 62
64 int * float 연산 오류 file 황제낙엽 2008.12.11 95
63 JavaScript Form Validation file 황제낙엽 2008.11.24 186
» 정규식 정리 황제낙엽 2008.11.24 252
61 setTimeout() / setInterval() 메소드 황제낙엽 2008.11.05 111
60 [key:value] 형태로 object를 저장할 수 있는 Static영역의 해쉬맵 클래스 (Map) 황제낙엽 2008.11.04 46
59 String xml 파싱 황제낙엽 2008.11.03 23
58 innerHTML 황제낙엽 2008.11.03 93