j

정규식 표현법

· 12년 전 · 6755
본 문서의 저작권은 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
\B\b 를 제외한 전부 /\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\d 를 제외한 전부 /\D/g
  • 7 eight 9
  • 12?3
\fform-feed
\nnew line
\rcarriage return
\swhite space
ex>탭, 띄어쓰기, \n, \r
/k\s/g
  • korea
  • blank is
  • blank
\S\s 를 제외한 전부 /k\S/g
  • korea
  • blank is
\t
\vvertical tab
\w알파벳+숫자+_. [A-Za-z0-9_]와 동일 /\w/g
  • !@#$%^&*()+_-[]{}\|"':;,.<>?/
\W\w 빼고 전부 /\W/g
  • !@#$%^&*()+_-[]{}\|"':;,.<>?/
\n\n이 자연수일때, ()로 지정한 n번째 정규식 /(.{2})e tru\1 is out \1ere/
  • the truth is out there ...
    1th :th
(th)가 \1로 지정된다.
\xhhhh는 hexacode, /[\x21-\x40]/g
  • !@#$%^&*()po
Code table 보기
\uhhhhhhhh는 hexacode, /[\u3131-\u3163\uac00-\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
/^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.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-z\d\-]{2,}\.)+[a-z]{2,})(:\d{1,5})?(\/[^\?]*)?(\?.+)?$/i
/^[ㄱ-ㅣ가-힣]+$/
  • 티맥스소프트
  • ㅜㅜ
  • ㅎㅎ

5. Javascript 정규식 함수

함수코드예제코드설명
Array RegExp.exec (to be checked)

var myRe=/d(b+)(d)/ig;
var myArray = myRe.exec("cdbBdbsbz");

/d(b+)(d)/gi

  • cdbBdbsbz
    1th :bB
    2th :d
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)/gi

  • cdbBdbsbz
    1th :bB
    2th :d
실행결과: checked = true;
String RegExp.toString()

var myRe=/d(b+)(d)/ig;
var str = myRe.toString();
document.write(str);

실행 결과: /d(b+)(d)/gi
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: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
|
댓글을 작성하시려면 로그인이 필요합니다. 로그인

프로그램

태그 필터 (최대 3개) 전체 개발자 소스 기타 mysql 팁자료실 javascript php linux flash 정규표현식 jquery node.js mobile 웹서버 os 프로그램 강좌 썸네일 이미지관련 도로명주소 그누보드5 기획자 견적서 계약서 기획서 마케팅 제안서 seo 통계 서식 통계자료 퍼블리셔 html css 반응형 웹접근성 퍼블리싱 표준화 반응형웹 홈페이지기초 부트스트랩 angularjs 포럼 스크린리더 센스리더 개발자톡 개발자팁 퍼블리셔톡 퍼블리셔팁 기획자톡 기획자팁 프로그램강좌 퍼블리싱강좌
+
제목 글쓴이 날짜 조회
12년 전 조회 1,625
12년 전 조회 979
12년 전 조회 1,996
12년 전 조회 1,394
12년 전 조회 3,058
12년 전 조회 2,572
12년 전 조회 1,925
12년 전 조회 2,398
12년 전 조회 1,880
12년 전 조회 1,655
12년 전 조회 1,049
12년 전 조회 1,163
12년 전 조회 5,581
12년 전 조회 2,629
12년 전 조회 3,106
12년 전 조회 1,767
12년 전 조회 1,478
12년 전 조회 829
12년 전 조회 1,840
12년 전 조회 945
12년 전 조회 1,522
12년 전 조회 2,790
12년 전 조회 2,357
12년 전 조회 1,701
12년 전 조회 6,680
12년 전 조회 2,512
12년 전 조회 728
12년 전 조회 681
12년 전 조회 1,431
12년 전 조회 2,075
12년 전 조회 916
12년 전 조회 724
12년 전 조회 1,357
12년 전 조회 1,491
12년 전 조회 719
12년 전 조회 1,145
12년 전 조회 1,420
12년 전 조회 807
12년 전 조회 1,103
12년 전 조회 3,690
12년 전 조회 1,440
12년 전 조회 981
12년 전 조회 866
12년 전 조회 1,237
12년 전 조회 1,469
12년 전 조회 4,257
12년 전 조회 5,588
12년 전 조회 717
12년 전 조회 2,286
12년 전 조회 6,756
12년 전 조회 2,428
12년 전 조회 9,348
12년 전 조회 555
12년 전 조회 756
12년 전 조회 1,368
12년 전 조회 1,687
12년 전 조회 1,340
12년 전 조회 1,953
12년 전 조회 2,365
12년 전 조회 3,221
12년 전 조회 2,185
12년 전 조회 2,357
12년 전 조회 2,334
12년 전 조회 1,613
12년 전 조회 1,413
12년 전 조회 1,057
12년 전 조회 1,247
12년 전 조회 2,036
12년 전 조회 1,584
12년 전 조회 1,296
12년 전 조회 2,337
12년 전 조회 2,064
12년 전 조회 1,908
12년 전 조회 1,644
12년 전 조회 2,340
12년 전 조회 1,150
12년 전 조회 804
12년 전 조회 424
12년 전 조회 565
12년 전 조회 1,069
12년 전 조회 2,488
12년 전 조회 2,501
12년 전 조회 1,583
12년 전 조회 1,203
12년 전 조회 991
12년 전 조회 9,114
12년 전 조회 620
12년 전 조회 1,588
12년 전 조회 1,176
12년 전 조회 1,626
12년 전 조회 1,829
12년 전 조회 1,020
12년 전 조회 1,596
12년 전 조회 2,233
12년 전 조회 1,365
12년 전 조회 1,308
12년 전 조회 1,213
12년 전 조회 7,445
12년 전 조회 1,343
12년 전 조회 1,208
🐛 버그신고