출처1)정규표현식 패턴들 - 생활코딩
출처2)모던 JavaScript 튜토리얼 - 패턴과 플래그
특정한 조건의 문자를 '검색'하거나 '치환'하는 과정을 매우 간편하게 처리 할 수 있도록 하는 수단이다. (출처: 생활코딩)
자바스크립트에서는 RegExp 객체와 문자열 메소드를 조합해 정규표현식을 사용한다.
regexp = new RegExp("pattern", "flags");
regexp = /pattern/;
regexp = /pattern/flag;
/찾으려고 하는 문자열/
/Hello/g → Hello World!/hello/→ Hello World!^특정 문자열
/^who/g → who is who특정 문자열$
/who$/m → who is who^$ → $12$ \-\ $25$\
$같은 기능을 가진 문자를 일반 텍스트로 바꾼다. (\ 뒤에 오는 문자를 일반 문자열로 escape시킨다고 생각하면 될 것 같다)/\$/g → $12$ \-\ $25$/^\$/g → $12$ \-\ $25$^)에 오는 '$'만 찾는다./\$$/m → $12$ \-\ $25$$)에 오는 '$'만 찾는다./\\/g → $12$ \-\.
/./g → Hello World 123!@/....../g → Regular expressions are powerful!!!/./g → O.K./\./g → O.K./\..\./g → O.K.\. : 문자 '.'. : 모든 문자(1자리)\. : 문자 '.'[찾으려는 문자 후보군]
/[oyu]/g → How do you do?/[dH]./g → How do you do?[dH] : d또는 H (1글자). : 모든 문자 (1글자)/[owy][yow]/g → How do you do?[owy] : o 또는 w 또는 y 1글자[yow] : y 또는 o 또는 w 1글자[-]
[]안에 원하는 모든 문자열을 넣기에는 무리가 있다./[C-K]/g → ABCDEFGHIJKLMNOPQRSTUVWXYZ/[a-d]/ → abcdefghijklmnopqrstuvwxyz/[C-Ka-d2-6]/g → ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789[^특정 문자열]
/[^CDghi45]/g → ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789(문자열1 | 문자열2 | ...)
/(on|ues|rida)/g → Monday Tuesday Friday/(Mon|Tues|Fri)day/g → Monday Tuesday Friday/..(id|esd|nd)ay/g → Monday Tuesday Friday.. : 2자리 문자(id|esd|nd) : 'id' 또는 'esd' 또는 'nd'ay : 'ay'문자열*
/a*b/g → aabc abc bc문자열+
/a+b/g → aabc abc bc문자열?
/a?b/g -> aabc abc bc{최소갯수, 최대갯수}
/.{5}/g → One ring to bring them all and in the darkness bind them/[els]{1,3}/g → One ring to bring them all and in the darkness bind them/[a-z]{3,}/g → One ring to bring them all and in the darkness bind them*? : ?가 뒤에 붙으면 *의 의미가 ?에 의해 0을 나타내게 된다.+? : ?가 뒤에 붙으면 +의 의미가 ?에 의해 1을 나타내게 된다.?? : ?가 뒤에 붙으면 ?의 의미가 ?에 의해 0을 나타내게 된다./r.*?/g → One ring to bring them all and in the darkness bind them.)0개이어야 한다(*?때문에 의미가 바뀜). 따라서 r만을 나타낸다./r.+?/g → One ring to bring them all and in the darkkness bind them.)1개이어야 한다(+?)때문에 의미가 바뀜)./r.??/g → One ring to bring them all and in the darkness bind them.)0개이어야 한다(??때문에 의미가 바뀜). 따라서 r만을 나타낸다./<div>.+</div>/ → <div>test</div><div>test2</div>/<div>.+?</div>/ → <div>test</div> <div>test2</div>상황에 따라 적절한 수량자를 사용해야겠다.
\w/[A-z0-9_]/와 같다. 알파벳 대소문자, 숫자, _ 를 모두 포함한다./\w/g → A 1 B 2 c 3 d _ 4 e:5 f f G G 7 7-- _ _--/\w*/g → A1 B2 c3 d_4 e:5 ffGG77--__--\w의 범위에 해당하는 문자들이 올 수도 있고 안 올 수도 있다./[a-z]\w*/g → A1 B2 c3 d_4 e:5 ffGG77--__--\w에 해당하는 문자들이 올 수도 있고 안 올 수도 있다.\W[^A-z0-9_]와 같다.\w와 정반대의 의미이다./\W/g → AS _34:AS11.23 @#$%12^*\d[0-9]와 같다./\d/g → Page 123; published: 1234 id=12#24@112\D\d와 정반대의 의미이다.[^0-9]와 같다./\D/g → Page 123; published: 1234 id=12#24@112\b/\b\w/g → Ere iron was found or tree was hewn, When young was mountain under moon;
\w 앞에 word boundary를 붙여서 단어의 맨 앞글자만 선택했다./\w\b/g → Ere iron was found or tree was hewn, When young was mountain under moon;
\w 뒤에 word boundary를 붙여서 단어의 맨 뒷글자만 선택했다./\bcat/g → cat concat
/cat\b/g → cat concat
\B\b의 반대이다./\b./g → cat concat/\B./g → cat concat/\B.\B/g → cat concat?= : 뒤에 오는 문자를 찾아서 나타낼때는 뒤에 오는 문자를 제외한다(예시를 봐야 이해가 간다)/\w+(?=X)/g → AAAX---aaax---111/\w+/g → AAAX---aaax---111/\w+(?=\w)/g → AAAX---aaax---111\w+ : AAA, aaa, 11(?=\w) : 뒤에 1자리 문자열str.match(regexp)
let str = "We will, we will rock you";
console.log(str.match(/we/gi)); // We,we
→ i플래그를 같이 사용하여 대소문자 구분 없이 검색한다.
let str = "We will, we will rock you";
let result = str.match(/we/i);
console.log(result[0]); // We
console.log(result.length); // 1
console.log(result.index); // 0(문자열의 위치)
console.log(result.input); // We will, we will rock you(원본 문자열)
→ 참고) 정규식을 괄호로 둘러싸면 메소드 호출 시 배열에 0이외에도 다른 index가 있을 수 있다.Capturing groups
str.match(pattern) || []
str.replace(regexp, replacement)
console.log("We will, we will".replace(/we/i, "I")); // I will, we will
console.log("We will, we will".replace(/we/ig, "I")); // I will, I will
regexp.test(str)
let str = "I love JavaScript";
let regexp = /LOVE/i;
console.log(regexp.test(str)); // true
정규표현식 테스트해볼 수 있는 사이트! regexr.com
얼렁뚱땅 알고있던 정규표현식을 생활코딩 영상과 모던자바스크립트 튜토리얼 사이트를 보면서 정리해보았다. 하나하나만 보면 알겠는데.. 응용을 하려니 어려워진다😥 많이 사용해서 익숙해져야겠다!