-
[JS] 정규표현식(Regular Expressions)Web/JS 2022. 2. 11. 11:51SMALL
정규식에서 쓰이는 메소드
1. exec
2. test
3. match
4. search
5. replace
6. split
freecodecamp에서 배운 정규표현식 내용들을 정리하였다.
1. .test() 메소드
let testStr = "freeCodeCamp"; let testRegex = /Code/; testRegex.test(testStr); //true
2. operator |
let petString = "James has a pet cat."; let petRegex = /dog|cat|bird|fish/; let result = petRegex.test(petString); //cat이 있기 때문에 true
3. Ignore Case While Matching
let myString = "freeCodeCamp"; let fccRegex = /freecodecamp/i; let result = fccRegex.test(myString); //소문자든 대문자든 문장이 일치하므로 true
4. .match() 메소드
let extractStr = "Extract the word 'coding' from this string."; let codingRegex = /coding/; let result = extractStr.match(codingRegex) //['coding']
5. 1개 이상의 매치를 찾을 때
let twinkleStar = "Twinkle, twinkle, little star"; let starRegex = /twinkle/gi; // let result = twinkleStar.match(starRegex); //['Twinkle','twinkle']
6. Wildcard Period(.)
// so that it matches the strings run, sun, fun, pun, nun, and bun let exampleStr = "Let's have fun with regular expressions!"; let unRegex = /.un/; // let result = unRegex.test(exampleStr); //fun이 포함되므로 true let exampleStr2 = 'sdf23l.kj?l.3sdl)^fk..1sdf8'; let regex = \W.\. //?l.
7. Match Single Character with Multiple Possibilities
let quoteSample = "Beware of bugs in the above code; I have only proved it correct, not tried it."; let vowelRegex = /[aeiou]/gi; let result = quoteSample.match(vowelRegex); // ['e','a'.'r' ...] 25개 추출
8. 알파벳 범위, 숫자 범위 제한
let catStr = "cat"; let batStr = "bat"; let matStr = "mat"; let bgRegex = /[a-e]at/; catStr.match(bgRegex); batStr.match(bgRegex); matStr.match(bgRegex); //["cat"], ["bat"], null let quoteSample = "Blueberry 3.141592653s are delicious."; let myRegex = /[h-s2-6]/gi; let result = quoteSample.match(myRegex); // ['l', 'r', 'r', '3', '4', '5', '2', '6', '5', '3', 's', 'r', 'l', 'i', 'i', 'o', 's']
9. 제외하고 추출: [^]
., !, [, @, / 와 같은 기호, 공백이 포함됨을 주의하자.
let quoteSample = "3 blind mice."; let myRegex = /[^0-9^aeiou]/gi; let result = quoteSample.match(myRegex); // [' ','b','l','n','d',' ','m','c','.']
10. 한 번 이상 연속되는 문자열 추출
let difficultSpelling = "Mississippi"; let myRegex = /s+/gi; let result = difficultSpelling.match(myRegex); //['ss', 'ss']
11. 0회 이상 반복하는 문자열 추출
let phrase = "ba humbug"; let regexPlus = /bah+/; let regexStar = /bah*/; regexPlus.test(phrase); // returns false regexStar.test(phrase); // returns true let phrase = "wooooow look at that!"; let regexPlus = /wo+w/; let regexStar = /wo*w/; regexPlus.test(phrase); // returns true regexStar.test(phrase); // returns true
12. Lazy matching: ?
정규표현식은 두 가지의 매칭 방법이 있다.
1. greedy matching - 가능한 가장 긴 문자열을 찾음. 정규표현식의 디폴트값.
const str = ` <div> <h1>Hello world</h1> </div> `; const greedyRegex = /<.+>/g; str.match(greedyRegex); // ['<div>','<h1>Hellow world</h1>','</div>']
2. lazy matching - 가능한 가장 짧은 문자열을 찾음. ? 기호를 붙여서 사용.
const str = ` <div> <h1>Hello world</h1> </div> `; const greedyRegex = /<.+?/g; str.match(greedyRegex); // ['<div>','<h1>','</h1>','</div>']
13. Beginning string pattern: ^
[^](제외)과 혼동하지 않도록 하자
let firstString = "Ricky is first and can be found."; let firstRegex = /^Ricky/; firstRegex.test(firstString); //true let notFirst = "You can't find Ricky now."; firstRegex.test(notFirst); //false
14. Ending String Patterns: $
let theEnding = "This is a never ending story"; let storyRegex = /story$/; storyRegex.test(theEnding); //true let noEnding = "Sometimes a story will have to end"; storyRegex.test(noEnding); //false
15. 모든 문자, 숫자, _: \w
[A-Za-z0-9_]의 shortcut 구문이다. 모든 문자의 대문자, 소문자, 숫자, 언더스코어(_)가 포함된다.
let quoteSample = "The five boxing wizards jump quickly."; let alphabetRegexV2 = /\w/g; let result = quoteSample.match(alphabetRegexV2).length; //31
반대는 \W이며 [^A-Za-z0-9_]의 shortcut이다.
let shortHand = /\W/; let numbers = "42%"; let sentence = "Coding!"; numbers.match(shortHand); //["%"] sentence.match(shortHand); //["!"]
16. 모든 숫자: \d (반대는 \D)
let movieName = "2001: A Space Odyssey"; let numRegex = /\d/g; let result = movieName.match(numRegex).length; //4
17. Specify Upper and Lower Number of Matches
let A4 = "aaaah"; let A2 = "aah"; let multipleA = /a{3,5}h/; multipleA.test(A4); //true multipleA.test(A2); //false let haStr = "Hazzzzah"; let haRegex = /Haz{4,}ah/g; //z가 최소 4개 이상 let result = haRegex.test(haStr); let timStr = "Timmmmber"; let timRegex = /Tim{4}ber/; //m이 4번만 let result = timRegex.test(timStr);
연속하는 a 개수의 범위를 정할 수 있다. {start, end}를 통해 범위를 지정한다.
18. Check for zero or one of the preceding element: ?
let american = "color"; let british = "colour"; let rainbowRegex= /colou?r/; rainbowRegex.test(american); //true rainbowRegex.test(british); //true
19. Positive and Negative Lookahead
let quit = "qu"; let noquit = "qt"; let quRegex= /q(?=u)/; let qRegex = /q(?!u)/; quit.match(quRegex); noquit.match(qRegex); //both of these return ["q"]
해당 문자열이 있는지 없는지 확인하는 구문이다.
positive lookahead는 (?=), negative lookahead는 (?!)로 확인한다.
20. Check For Mixed Grouping of Characters
let testStr = "Pumpkin"; let testRegex = /P(engu|umpk)in/; //penguin or pumpkin testRegex.test(testStr); //true let myString = "Eleanor Roosevelt"; let myRegex = /(Franklin|Eleanor).* Roosevelt/g; let result = myRegex.test(myString); //it checks for the names of Franklin Roosevelt or Eleanor Roosevelt //in a case sensitive manner and it should make concessions for middle names.
( )와 | 오퍼레이터를 사용한다.
21. Reuse Patterns Using Capture Groups
설명을 봐도 아직 100% 이해하지 못해서 더 많은 예제를 보며 공부해야할 것 같다.
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/debugging/use-the-javascript-console-to-check-the-value-of-a-variable
www.freecodecamp.org
let repeatStr = "row row row your boat"; let repeatRegex = /(\w+) \1 \1/; repeatRegex.test(repeatStr); // Returns true repeatStr.match(repeatRegex); // Returns ["row row row", "row"]
freeCodeCamp Challenge Guide: Reuse Patterns Using Capture Groups
Reuse Patterns Using Capture Group Hints Hint 1 Given code below: let testString = "test test test"; let reRegex = /(test)\s\1/; let result = reRegex.test(testString); result will match only test test because \1 in this example stands for the same text as
forum.freecodecamp.org
22. .replace(찾고싶은 패턴, 바꿀 내용)
let wrongText = "The sky is silver."; let silverRegex = /silver/; wrongText.replace(silverRegex, "blue"); //The sky is blue
$ 기호를 통해 캡처 그룹에 접근할 수 있다.
"Code Camp".replace(/(\w+)\s(\w+)/, '$2 $1'); //Camp Code let str = "one two three"; let fixRegex = /(\w+)\s(\w+)\s(\w+)/; let replaceText = "$3 $2 $1"; let result = str.replace(fixRegex, replaceText); //three two one
\d: 숫자 매치
\w: 숫자 혹은 문자 매치
\s: 공백 매치(space, linebreak or tab)
\D: 숫자 아닌거 매치
\W: 숫자나 문자가 아닌거 매치(?,&,...)
\S: 공백 아닌거 매치
반응형'Web > JS' 카테고리의 다른 글
[JS] Closure (0) 2022.05.12 [JS] Constructor Function (0) 2022.05.06 [JS] 소수점을 버리고 자연수를 얻는 방법 (0) 2022.01.17