본문 바로가기

WEB/JavaScript

Regular Expressions

regular expression 찾기

. test() 메소드 이용

대소문자 구분하고, 참/거짓 리턴

let myString = "Hello World";
let myRegex = /Hello/;
let result = myRegex.test(myString); //boolean 리턴

OR 이용하기

let myRegex = /yes|no|maybe/;

대소문자 무시 : i flag 이용

let myRegex = /IgNoreCasE/i;

.match() 메소드 이용

문자열 추출

let myString = "Hello World";
let myRegex = /Hello/;
myString.match(myRegex);

반복적으로 찾기 : g flag 이용

let myRegex = /Repeat/g;

Wildcard . 이용

let myRegex = /.ox/;

box, fox 등 ox로 끝나는 단어들 리턴

Multiple Possibilities : [] 이용

let myRegex = /b[aeiou]g/;

b로 시작하고, 중간에 aeiou가 있고, g가 있는 단어 리턴

연속적인 범위에 속하는 단어 찾기

let myRegex = /[a-e]/; //알파벳 가능
let myRegex2 = /[0-8]/; //숫자 가능
let myRegex3 = /a-z0-9/; //알파벳 숫자 혼용 가능

Negated character sets : [^ ] 이용

특정 알파벳만 제외하고 찾기

let myRegex = /[^aeiou]/;

한 번 이상 반복되는 문자: + 이용

let myRegex = /s+/g;

0번 이상 반복되는 문자 : * 이용

let myRegex = /go*/;
//"goooo" , "g" 리턴

Lazy Matching : ? 이용

기본적으로 Regular Expressions에서는 greedy 하게 가장 긴 string을 찾는다.

반면, lazy match에서는 가장 작은 부분을 리턴한다.

let myRegex = /<.*?>/;
//html 헤더들 리턴 (e.g. <h1>)

Match Beginning String Patterns : ^

^[ ]안에 쓰지 않고 그냥 / /안에 사용하면 문자열의 시작부분에서 expression을 찾는 데에 사용된다.

let firstString = "James can be found.";
let firstRegex = /^James/;
firstRegex.test(firstString); //true
let notFirst = "You can't find James now.";
firstRegex.test(notFirst); //false

Match Ending String Patterns : $

Regular Expression의 마지막 문자를 정해줄 수 있다.

let string1 = "Goodbye my friends"
let lastRegex = /bye$/;
lastRegex.test(string1); //false
let string2 = "bye bye";
lastRegex.test(string2); //true

모든 문자와 숫자 찾기 : \w

\w[A-Za-z0-9_]와 같다. 즉, 모든 대소문자와 숫자, 언더바를 포함한다.

let shortHand = /\w+/;
let string = "hello21";
shortHand.test(string);

모든 문자와 숫자 제외하기 : \W

\W[^A-Za-z0-9_]와 같다. 즉, 모든 대소문자와 숫자, 언더바를 제외한다

let shortHand = /\W+\;
let string = "Hello World!";
string.match(shortHand); //!

모든 숫자 찾기: \d

\d[0-9]와 같다.

let id = "helloJwon21";
let numRegex = /\d/g;
id.match(numRegex); //21;

모든 숫자 제외하기 : \D

\D[^0-9]와 같다.

let id = "helloJwon21";
let noNumRegex = /\D/g;
id.match(noNumRegex); //helloJwon;

WhiteSpace

whitespace: \s

carriage return: \r

tab: \t

form feed: \f

new line: \n

vertical tab: \v

Non-Whitespace Characters

\S : whitespace, carriage return, tab, form feed, new line characters 제외

let sample = "Count the non-white space.";
let countNonWhiteSpace = /\S/g;
let result = sample.match(countNonWhiteSpace);

Quantity Specifiers : { }

{ }이용해서 특정 문자 개수의 범위 지정가능

문자{최소값,최대값} 또는 문자{개수}

let multipleA = /a{3,5}h/;

Possible existence : ?

존재할 수도, 존재하지 않을 수도 있는 문자

let myRegex = /favou?rite/;

Lookahead

positive lookahead (?=...)

특정 요소가 있는지 확인.

negative lookahead (?!...)

특정 요소가 존재하지 않음을 확인

let password = "abc123";
let checkPass = /(?=\w{3,6})(?=\D*\d)/;
checkPass.test(password);

반복되는 패턴 - capture group 이용

반복되는 substring은 ( )으로 묶기

반복되는 substring이 나타날 부분에 \숫자 사용(숫자는 그룹마다 할당되며, 1부터 시작)

let reRegex = /^(\d+) \1 \1$/;

replace()

특정 문자열을 찾아서 다른 것으로 바꾼다.

replace(바꾸기 전 문자열, 바꾼 후 문자열)

let wrongText = "The weather is cold"
let Regex = "cold"
wrongText.replace(Regex,"hot");

//capture group 이용도 가능하다
"one two three".replace(/(\w+)\s(\w+)\s(\w+)/, '$3 $2 $1'); 

'WEB > JavaScript' 카테고리의 다른 글

자바스크립트 객체지향프로그래밍(OOP)  (0) 2021.08.06
자바스크립트 - 기본 자료 구조  (0) 2021.07.31