웹프로그래밍

Global It Leader!!


jQuery


 
 

정규식 예제

페이지 정보

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

본문

함수 코드예제 코드설명
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 +";
");

/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 "" + str + "";
}
).replace(/\n/, "
");
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] +"
");
}

document.write("비교
");

var str = "ABCdEFgHiJKL";
var myResult = /[a-z]/g.exec(str);
for(var cnt = 0 ; cnt < myResult.length; cnt++){
document.write(cnt +":" + myResult[cnt] +"
");
}

실행 결과:
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] +"
");
}

실행 결과:
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 = "blah soft";
document.write(str +"
");
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+ "==============
");
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) + "
");
document.write(number_format("-9876543.21987")+ "
");
document.write(number_format("-123456789.12")+ "
");

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 

 

댓글목록

등록된 댓글이 없습니다.

전체 142
게시물 검색
jQuery 목록
번호 제목 글쓴이 조회 날짜
62 no_profile 오원장 쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 4061 11-29
61 no_profile 오원장 쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 6631 09-17
60 no_profile 오원장 쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 5508 08-21
59 no_profile 오원장 쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 4858 08-21
58 no_profile 오원장 쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 6419 07-13
57 no_profile 오원장 쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 5980 06-13
56 no_profile 오원장 쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 5311 04-28
55 no_profile 오원장 쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 5486 04-24
54 no_profile 오원장 쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 4870 04-24
53 no_profile 오원장 쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 5767 04-24
52 no_profile 오원장 쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 4828 04-24
51 no_profile 오원장 쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 4395 04-20
50 no_profile 오원장 쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 4023 04-19
49 no_profile 오원장 쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 4387 04-19
48 no_profile 오원장 쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 4035 04-17
47 no_profile 오원장 쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 4346 04-11
열람중 no_profile 오원장 쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 4413 04-01
45 no_profile 오원장 쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 4578 04-01
44 no_profile 오원장 쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 4279 03-31
43 no_profile 오원장 쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 4346 03-22