자바스크립트 - 정규표현식 정리 > JQuery & JavaScript

STUDY ROOM

JQuery & JavaScript

자바스크립트 - 정규표현식 정리

페이지 정보

작성자 JMStudy 작성일07-04-05 17:08 조회8,058회 댓글0건

본문

Regular Expression(정규 표현식) 

정규 표현식이란, 문자열에서 특정한 캐릭터 조합(character combination)을 찾아내기위한 패턴(pattern)입니다. 

쉽게 문장에서 특정한 단어를 찾아내는 것이라고 생각하시면 될 것 같습니다 

그렇기 때문에 정규 표현식 함수라고 불리는 것들은 대부분 문자열과 관련하여 특정 변수로 저장된 문자열 내에서 지정한 문자를 찾아내는 기능들을 수행합니다. 

일반적으로 - 어느 랭귀지를 사용하던지 간에 - 정규 표현식을 구성하는 방법은 일반적인 문자열과 특정한 의미를 지니는 메타문자를 조합하는 것입니다. 


JavaScript에서 정규 표현식은 1.2 버젼부터 사용가능하도록 추가되었습니다. 즉 그 이하버젼에서는 사용하지 못한다는 말이므로 아주 오래된 고려적 웹브라우저를 사용하시는 분들은 절대로 볼수가 없습니다. -_-;; 

자바스크립트 객체부에서는 언급을 하지 않고 있지만, 정규표현식은 객체(objects)입니다. 

정규 표현식의 패턴(pattern)은 object initializers(예, /abc/) 또는 RegExp constructor function(예, re = new RegExp("abc")로 표현할수 있습니다. 

이러한 패턴들은 정규표현식의 exec, method 메소드(method)나 String 객체의 match, replace, search, split 메소드에서 함께 사용됩니다. 



Regular Expression(정규 표현식) 생성 

1. object initializers를 사용한 방법 



re = /ab+c/ 


2. RegExp 객체의 constructor function를 사용한 방법 



re = new RegExp("ab+c") 


Regular Expression(정규 표현식) 쓰기 

정규 표현식 패턴은 /abc/ 같은 단순한 캐릭터나 /ab*c/ ,/Chapter (\d+)\.\d*/ 와 같은 단순 캐릭터와 특별한 캐릭터의 조합으로 나타낼수 있습니다. 

다음에 정규 표현식에 사용하는 특수 문자들에 대한 표를 나타내었지만, 이 외에도 상당히 많은 내용들이 있습니다. 

타 사이트나 책을 참고로 하여 보시기 바랍니다. 



정규 표현식에서 사용하는 Special characters 

Character 

의미 


\ 다음에 나오는 특수 문자를 문자열로 인식 

가령, /라는 특수문자는 일반적으로 프로그램상에서 나누기로 인식하게 되어있습니다. 이것을 나누기가 아닌 그냥 문자열 / 로 인식시키려면 \/ 로 써주면됩니다. 


라인의 처음과 패턴과 매치 

가령, ^A 라고 써주면 검색하고자 하는 문장의 시작문자가 A인지를 검사하는 것입니다.   

라인의 끝과 패턴과 매치 

가령, ^A 라고 써주면 검색하고자 하는 문장의 마지막문자가 A인지를 검사하는 것입니다.   

0개 이상의 문자와 매치(모든것이라는 의미) 


1개 이상의 문자와 매치, {1,}와 같은 의미임. 


0 또는 1개의 문자 의미. 

즉, A?b 라면 A라는 문자와 b라는 문자사이에 문자가 0개 또는 1개 가 들어갈 수 있다는 말입니다. 즉, Ab, Aab, Acb등과 같은.. 


1개의 문자와 일치 


() 

한번 match를 수행해서 나온 결과를 기억함. 

예: /(foo)/ 는 foo라는 단어를 검색한 후, 그 단어를 배열등과 같은 저장장소에 남겨두어 나중에 다시 호출할 수 있도록 합니다. 


OR 


{n} 

정확히 n개의 문자 

예: a{2} 는 a 문자 두 개, 즉, aa를 의미합니다. 


{n,} 

n개 이상의 문자 


{n,m} 

n이상 m이하의 문자 


[xyz] 

문자들의 set를 의미. 가령, [a-z]라면 a부터 z까지의 모든 문자와 매치하는 것으로 []안의 -는 범위를 나타냅니다. 


[^xyz] 

네가티브(-) 캐릭터 셋 


[\b] 

백스페이스와 매치 


\b 

단어의 시작 또는 끝에서 빈 문자열과 매치 


\B 

단어의 시작 또는 끝이 아닌 곳에서의 빈 문자열과 매치 


\cX 

control 문자와 매치 


\d 

0부터 9까지의 아라비아 숫자와 매치. [0-9]과 같은 의미 


\f 

form-feed와 매치 


\n 

linefeed와 매치 


\r 

캐리지 리턴과 매치 


\s 

화이트스페이스 문자와 매치. [ \t\n\r\f\v]과 같은 의미 


\S 

\s가 아닌 문자들과 매치. [^ \t\n\r\f\v]과 같은 의미 


\t 

탭 의미 


\v 

수직 탭 의미 


\w 

w는 문자가 아닌 0, 1, 2, 3 ... 등과 같은 숫자를 의미 


\W 

W는 문자가 아닌 요소, 즉 % 등과 같은 특수 문자를 의미함 


\n 

n은 마지막 일치하는 문장 


\ooctal 

\xhex 

8(octal)진수, 10(hex)진수 값 




Regular Expression(정규 표현식)과 함께 사용하는 함수들 

exec 

문장에서 매치를 위해 검색을 수행하는 정규 표현식 메소드 

배열을 리턴 


test 

문장에서 매치를 위해 테스트하는 정규표현식 메소드 

True 또는 False 리턴 


match 

문장에서 매치를 위해 검색을 수행하는 string 메소드 

배열 또는 null 문자 리턴 


search 

문장에서 매치를 위해 테스트하는 string 메소드 

목차나 -1 리턴 


replace 

문장에서 매치를 위해 검색을 실행하고 문장을 대체하는 String 메소드 


split 

문장에서 매치하는 부분을 배열에 할당하는 String 메소드 




이와 같은 정규 표현 식들의 실행 결과는 예제의 테스트를 통해 확인해 보도록 하십시요. 

<script language="JavaScript1.2"> 

myRe=/d(b+)d/g; 

myArray = myRe.exec("cdbbdbsbz"); 

document.writeln("The value of lastIndex is " + myRe.lastIndex); 

</script>   



<script language="JavaScript1.2"> 

myArray = /d(b+)d/g.exec("cdbbdbsbz"); 

document.writeln("The value of lastIndex is " + /d(b+)d/g.lastIndex); 

</script>   



<script language="JavaScript1.2"> 

re = /(\w+)\s(\w+)/; 

str = "John Smith"; 

newstr = str.replace(re, "$2, $1"); 

document.write(newstr) 

</script>   



<script language="JavaScript1.2"> 

function getInfo(){ 

re = /(\w+)\s(\d+)/ 

re.exec(); 

window.alert(RegExp.$1 + ", your age is " + RegExp.$2); 

</script> 

 

Enter your first name and your age, and then press Enter. 

<form> 

<input type="text" name="NameAge" onchange="getInfo(this);"> 

</form> 

 




<script language="JavaScript1.2"> 


// The name string contains multiple spaces and tabs, 

// and may have multiple spaces between first and last names. 



names = new String ( "Harry Trump ;Fred Barney; Helen Rigby ;\Bill Abel ;Chris Hand ") 

document.write ("---------- Original String" + "<BR>" + "<BR>") 

document.write (names + "<BR>" + "<BR>") 

// Prepare two regular expression patterns and array storage. 



// Split the string into array elements. 

// pattern: possible white space then semicolon then possible white space 



pattern = /\s*;\s*/ 



// Break the string into pieces separated by the pattern above and and store the pieces in an array called nameList 

nameList = names.split (pattern) 



// new pattern: one or more characters then spaces then characters. 

// Use parentheses to "memorize" portions of the pattern. 

// The memorized portions are referred to later. 



pattern = /(\w+)\s+(\w+)/ 



// New array for holding names being processed. 



bySurnameList = new Array; 



// Display the name array and populate the new array 

// with comma-separated names, last first. 

// The replace method removes anything matching the pattern 

// and replaces it with the memorized string--second memorized portion 

// followed by comma space followed by first memorized portion. 

// The variables $1 and $2 refer to the portions 

// memorized while matching the pattern. 



document.write ("---------- After Split by Regular Expression" + "<BR>") 

for ( i = 0; i < nameList.length; i++) { 

document.write (nameList[i] + "<BR>") 

bySurnameList[i] = nameList[i].replace (pattern, "$2, $1") 



// Display the new array. 



document.write ("---------- Names Reversed" + "<BR>") 

for ( i = 0; i < bySurnameList.length; i++) { 

document.write (bySurnameList[i] + "<BR>") 



// Sort by last name, then display the sorted array. 



bySurnameList.sort() 

document.write ("---------- Sorted" + "<BR>") 

for ( i = 0; i < bySurnameList.length; i++) { 

document.write (bySurnameList[i] + "<BR>") 

document.write ("---------- End" + "<BR>") 

</script>


댓글목록

등록된 댓글이 없습니다.