정규표현식
테스트 사이트
regex101: build, test, and debug regex
Regular expression tester with syntax highlighting, explanation, cheat sheet for PHP/PCRE, Python, GO, JavaScript, Java, C#/.NET, Rust.
regex101.com
기본
/a/ -> 문자열에 a란 글자가 있는가
/ab/ -> 문자열에 ab란 글자가 있는가
/[ab]/ -> 문자열에 a나 b란 글자가 있는가
/a(n|p)/ -> 문자열에 an이란 글자나 ap란 글자가 있는가
/a[np]/ -> 동일
/a[d-g]/ -> ad, ae, af, ag
/[a-zA-Z]/ -> 알파벳이 하나라도 들어가있는가
/[^a-zA-Z]/ -> 알파벳이 하나도 존재하지 않는가
반복
/gra?y/ -> gry, gray (a가 있을수도 있고 아닐수도 있습니다)
/gra*y/ -> gry, gray, graay... (a가 없거나 있거나 많거나)
/gra+y/ -> gray, graay... (a가 있거나 많거나)
/gra{2}y/ == /graay
/gra{2,4}y -> graay, graaay, graaaay
시작과 끝
/^a/ -> 문장이 a로 시작하는 경우
/a$/ -> 문장이 a로 끝나는 경우
/ \b a / -> a로 시작하는 단어가 존재하는 경우 *띄어쓰기는 편의상 넣은거!
/ a \b / -> a로 끝나는 단어가 존재하는 경우
/ \B a / -> a가 시작점이 아닌 곳에 존재하는 단어가 있는 경우
/ a \B / -> a가 끝이 아닌 곳에 존재하는 단어가 있는 경우
특수글자
/./ -> 모든 글자 (\n 제외)
/ \. / -> 마침표
\로 표기해야 되는 문자 = . [ ] { } ( ) \ ^ $ $ | ? * +
태그
/\d/ -> 숫자
/\D/ -> 숫자가 아닌 모든 글자
/\w/ -> 모든 문자(영어 숫자 밑줄) *한글은 아님!!!!!!!!!!!!
/\W/ -> w 아닌거
/\s/ -> 공백, 탭, 줄바꿈
/\S/ -> s 아닌거
\d{3} = 숫자 3개
플래그
//g = global = (값을 찾아도) 문자열이 끝날때 까지 계속 검색. replaceAll()에 주로 사용
//i = ignore case = 대소문자 구분 x
//m = multi line = ^$d와 함께 파일 입출력에 주로 사용.
//y = sticky = 지정한 lastIndex부터 탐색 시작
활용
var testStr = "테스트test";
//숫자 체크
var pattern1 = /[0-9]/; //숫자
if (pattern1.test(testStr)) {
alert("숫자가 포함됩니다."); //false
}
//영어 체크
var pattern2 = /[a-zA-Z]/; //영어
if(pattern2.test(testStr)){
alert("영어가 포함됩니다."); //true
}
//한글 체크
var pattern3 = /[ㄱ-ㅎ|ㅏ-ㅣ|가-힣]/; //한글
if(pattern3.test(testStr)){
alert("한글이 포함됩니다."); //true
}
//한글, 영어 둘다 포함해서 체크하고 싶을 때
if(pattern3.test(testStr) && pattern2.test(testStr)){
alert("한글 영어 모두 포함됩니다."); // true
}
메서드
const regex = /\d+/;
const result = regex.exec("123 apples and 456 bananas");
console.log(result); // ["123", index: 0, input: "123 apples and 456 bananas", groups: undefined]
exec(): 매치된 부분의 정보 반환
*test랑 exec만 regex가 앞에
const regex = /\d+/g;
const result = "123 apples and 456 bananas".match(regex);
console.log(result); // ["123", "456"]
match(): 매치된 모든 부분을 배열로 반환
const regex = /apples/;
console.log("123 apples and 456 bananas".search(regex)); // 4
console.log("123 bananas".search(regex)); // -1
search(): 매치된 부분의 인덱스 반환
const regex = /apples/g;
const result = "123 apples and 456 apples".replace(regex, "oranges");
console.log(result); // "123 oranges and 456 oranges"
replace(): 매치된 부분을 대체
const originalString = "apple apple apple";
const replacedString = originalString.replaceAll("apple", "orange");
console.log(replacedString); // "orange orange orange"
const regex = /a/g;
const replacedStringWithRegex = originalString.replaceAll(regex, "o");
console.log(replacedStringWithRegex); // "opple opple opple"
replaceAll(): 매치된 부분 전체 대체
*정규표현식에 g플래그 필수!
replace 활용
const text = "Hello, world!";
const replacedText = text.replace(/(\w+), (\w+)/, "$2 $1");
console.log(replacedText); // "world! Hello,"
$에 숫자를 사용하면 매치된 각 그룹을 참조한다
const text = "Hello, world? world!";
const replacedText = text.replaceAll(/world/g, "$&s");
console.log(replacedText); // Hello, worlds? worlds!
$&를 사용하면 매치된 전체 부분을 참조한다