티스토리 뷰

 

Test Method

let testStr = "freeCodeCamp";
let testRegex = /Code/;
testRegex.test(testStr);
// Returns true

 

// 사이에 quote 없음, regex가 메소드 앞에 옴. 

var str = "The best things in life are free";
var patt = new RegExp("e"); // 찾고자 하는 것을 아규먼트로 받을 때에 사용
var res = patt.test(str);

 

newRe = new RegExp('Fox','g') // Define a string. str1 = 'The Quick Brown Fox Jumps Over The Lazy Dog'; // Check whether regular expression exists in the string. newRe.test(str1)

 

 

여러 개 찾기(or)

You can also search for more than just two patterns. You can do this by adding more patterns with more ORoperators separating them, like /yes|no|maybe/.

 

 

Ignore Case While Matching

Case (or sometimes letter case) is the difference between uppercase letters and lowercase letters. Examples of uppercase are "A""B", and "C". Examples of lowercase are "a""b", and "c".

You can match both cases using what is called a flag. There are other flags but here you'll focus on the flag that ignores case - the iflag. (insensitive flag) You can use it by appending it to the regex. An example of using this flag is /ignorecase/i. This regex can match the strings "ignorecase""igNoreCase", and "IgnoreCase".

 

 

Match(한 번만 찾기)

"Hello, World!".match(/Hello/);
// Returns ["Hello"]
let ourStr = "Regular expressions";
let ourRegex = /expressions/;
ourStr.match(ourRegex);
// Returns ["expressions"]

테스트 메소드와 다르게 찾을 객체가 메소드 앞에 옴

 

Match(여러번 찾기)

To search or extract a pattern more than once, you can use the gflag. (global flag)

let repeatRegex = /Repeat/g;
testStr.match(repeatRegex);
// Returns ["Repeat", "Repeat", "Repeat"]

 

 

Multiple flags

You can have multiple flags on your regex like /search/gi

 

 

Match Anything with Wildcard Period

The wildcard character .will match any one character. The wildcard is also called dotand period. You can use the wildcard character just like any other character in the regex. For example, if you wanted to match "hug""huh""hut", and "hum", you can use the regex /hu./to match all four words.

 

 

Match Single Character with Multiple Possibilities

For example, you want to match "bag""big", and "bug"but not "bog". You can create the regex /b[aiu]g/to do this. The [aiu]is the character class that will only match the characters "a""i", or "u".

let bigStr = "big";
let bagStr = "bag";
let bugStr = "bug";
let bogStr = "bog";
let bgRegex = /b[aiu]g/;
bigStr.match(bgRegex); // Returns ["big"]
bagStr.match(bgRegex); // Returns ["bag"]
bugStr.match(bgRegex); // Returns ["bug"]
bogStr.match(bgRegex); // Returns null

 

 

 

Match Letters of the Alphabet

 

Inside a character set, you can define a range of characters to match using a hyphencharacter: -.

 

 

 

For example, to match lowercase letters athrough eyou would use [a-e].

 

 

 

Match Numbers and Letters of the Alphabet

let jennyStr = "Jenny8675309";
let myRegex = /[a-z0-9]/ig;
// matches all letters and numbers in jennyStr
jennyStr.match(myRegex);

//[]브라켓은 하나뿐

 

 

Match Single Characters Not Specified

To create a negated character set, you place a caretcharacter (^) after the opening bracket and before the characters you do not want to match.

For example, /[^aeiou]/gimatches all characters that are not a vowel. Note that characters like .![@/and white space are matched - the negated vowel character set only excludes the vowel characters.

let quoteSample = "3 blind mice.";
let myRegex = /[^aeiou^0-9]/gi; // 모음, 숫자 제외 - 조건이 두개, ^를 두번 쓴다
let result = quoteSample.match(myRegex);
 
 

 

Match Characters that Occur One or More Times

You can use the +character to check if that is the case. Remember, the character or pattern has to be present consecutively. That is, the character has to repeat one after the other.

For example, /a+/gwould find one match in "abc"and return ["a"]. Because of the +, it would also find a single match in "aabc"and return ["aa"].

If it were instead checking the string "abab", it would find two matches and return ["a", "a"]because the acharacters are not in a row - there is a bbetween them. Finally, since there is no "a"in the string "bcd", it wouldn't find a match.

 

 

Match Characters that Occur Zero or More Times

et soccerWord = "gooooooooal!";
let gPhrase = "gut feeling";
let oPhrase = "over the moon";
let goRegex = /go*/;
soccerWord.match(goRegex); // Returns ["goooooooo"]
gPhrase.match(goRegex); // Returns ["g"]
oPhrase.match(goRegex); // Returns null
 
 
 

 

Find Characters with Lazy Matching

 

You can apply the regex /t[a-z]*i/to the string "titanic". This regex is basically a pattern that starts with t, ends with i, and has some letters in between.

Regular expressions are by default greedy, so the match would return ["titani"]. It finds the largest sub-string possible to fit the pattern.

However, you can use the ?character to change it to lazymatching. "titanic"matched against the adjusted regex of /t[a-z]*?i/returns ["ti"].

 

Match Beginning String Patterns

In an earlier challenge, you used the caretcharacter (^) inside a character setto create a negated character setin the form [^thingsThatWillNotBeMatched]. Outside of a character set, the caretis used to search for patterns at the beginning of strings. // ^[a-z]는 스트링 앞에서 알파벳 찾는 것, [^a-z]는 반대 

 

Match Ending String Patterns

let theEnding = "This is a never ending story";
let storyRegex = /story$/;
storyRegex.test(theEnding);
// Returns true
let noEnding = "Sometimes a story will have to end";
storyRegex.test(noEnding);
// Returns false
 

 

Match All Letters and Numbers

Using character classes, you were able to search for all letters of the alphabet with [a-z]. This kind of character class is common enough that there is a shortcut for it, although it includes a few extra characters as well.

The closest character class in JavaScript to match the alphabet is \w. This shortcut is equal to [A-Za-z0-9_]. This character class matches upper and lowercase letters plus numbers. Note, this character class also includes the underscore character (_).

let longHand = /[A-Za-z0-9_]+/;
let shortHand = /\w+/;
let numbers = "42";
let varNames = "important_var";
longHand.test(numbers); // Returns true
shortHand.test(numbers); // Returns true
longHand.test(varNames); // Returns true
shortHand.test(varNames); // Returns true

let quoteSample = "The five boxing wizards jump quickly.";
let alphabetRegexV2 = /\w+/g; // +를 빼면 모든 알파벳 개수인 31을 리턴한다.
let result = quoteSample.match(alphabetRegexV2).length;
undefined
result;
6
quoteSample.match(alphabetRegexV2);
(6) ["The", "five", "boxing", "wizards", "jump", "quickly"]
 

 

Match Everything But Letters and Numbers

You can search for the opposite of the \w with \W. Note, the opposite pattern uses a capital letter. This shortcut is the same as [^A-Za-z0-9_].

let shortHand = /\W/;
let numbers = "42%";
let sentence = "Coding!";
numbers.match(shortHand); // Returns ["%"]
sentence.match(shortHand); // Returns ["!"]

 

Match All Numbers

The shortcut to look for digit characters is \d, with a lowercase d. This is equal to the character class [0-9], which looks for a single character of any number between zero and nine.

 
 

Match All Non-Numbers

The shortcut to look for non-digit characters is \D. This is equal to the character class [^0-9], which looks for a single character that is not a number between zero and nine.
 
 

Restrict Possible Usernames

//조건 : 1. 숫자는 스트링 끝에 들어가야만 한다. 2. 대문자, 소문자 가리지 않음. 3.알파벳은 스트링 앞에 위치하고, 적어도 2글자 이상 되어야 함. 2글자로 username을 만드려면 알파벳으로만 이루어져야 함.
 
let username = "JackOfAllTrades";
let userCheck = /^[a-z]{2,}\d*$/i; // 1. ^[a-z] 스트링 앞에서 알파벳 찾기 2. {2,} 적어도 두글자 이상 3.\d* 숫자가 없거나 있다. 4. $ 스트링 뒤에서 찾는다.
let result = userCheck.test(username);
 
 

Match Whitespace / Match Non-Whitespace

You can search for whitespace using \s, which is a lowercase s. You can think of it as similar to the character class [ \r\t\f\n\v]Search for non-whitespace using \S, which is an uppercase s.You can think of it being similar to the character class [^ \r\t\f\n\v].
 
let whiteSpace = "Whitespace. Whitespace everywhere!"
let spaceRegex = /\s/g;
whiteSpace.match(spaceRegex);
// Returns [" ", " "]
 
 
 

Specify Upper and Lower Number of Matches

For example, to match only the letter appearing between 3and 5times in the string "ah", your regex would be /a{3,5}h/.
let A4 = "aaaah";
let A2 = "aah";
let multipleA = /a{3,5}h/;
multipleA.test(A4); // Returns true
multipleA.test(A2); // Returns false
하한만 정하고 싶으면 {n, } 정확한 넘버 개수를 정하고 싶으면 {n}
 
 
 

Check for All or None

let american = "color";
let british = "colour";
let rainbowRegex= /colou?r/;
rainbowRegex.test(american); // Returns true
rainbowRegex.test(british); // Returns true
 
 
 

Positive and Negative Lookahead

positive lookaheadwill look to make sure the element in the search pattern is there, but won't actually match it. A positive lookahead is used as (?=...)where the ...is the required part that is not matched.

On the other hand, a negative lookaheadwill look to make sure the element in the search pattern is not there. A negative lookahead is used as (?!...)where the ...is the pattern that you do not want to be there. The rest of the pattern is returned if the negative lookahead part is not present.

let quit = "qu";
let noquit = "qt";
let quRegex= /q(?=u)/;
let qRegex = /q(?!u)/;
quit.match(quRegex); // Returns ["q"]
noquit.match(qRegex); // Returns ["q"]

The difference between ?= and ?! is that the former requires the given expression to match and the latter requires it to not match. For example a(?=b) will match the "a" in "ab", but not the "a" in "ac". Whereas a(?!b) will match the "a" in "ac", but not the "a" in "ab".

The difference between ?: and ?= is that ?= excludes the expression from the entire match while ?: just doesn't create a capturing group. So for example a(?:b) will match the "ab" in "abc", while a(?=b) will only match the "a" in "abc". a(b) would match the "ab" in "abc" and create a capture containing the "b".

 

Use lookaheads in the pwRegex to match passwords that are greater than 5 characters long and have two consecutive digits. // 병렬적인 조건 체크에도 사용되는 듯 하다.

let sampleWord = "astronaut"; let pwRegex = /(?=\w{5,})(?=\D*\d{2})/; /alphanumeric 5글자 이상, \D(not 숫자)*(있어도 되고 없어도 됨), \d 숫자 연속 2개 이상) let result = pwRegex.test(sampleWord);

 

 

Reuse Patterns Using Capture Groups

You can search for repeat substrings using capture groups. Parentheses, (and ), are used to find repeat substrings. You put the regex of the pattern that will repeat in between the parentheses.
To specify where that repeat string will appear, you use a backslash (\) and then a number. This number starts at 1 and increases with each additional capture group you use. An example would be \1to match the first group.
 
let repeatStr = "regex regex";
let repeatRegex = /(\w+)\s\1/; 
repeatRegex.test(repeatStr); // Returns true
repeatStr.match(repeatRegex); // Returns ["regex regex", "regex"]
 
let testString = "test test test "; let reRegex =/(test)(\s)\1\2\1/; // capturing group 하나당 넘버 붙임(test가 1, \s가 2) let result = reRegex.test(testString);
 
Use capture groupsin reRegexto match numbers that are repeated only three times in a string, each separated by a space.
 
let repeatNum = "42 42 42"; let reRegex =  /^(\d+)\s\1\s\1$/; // 딱 세번만 반복되도록 했으므로 ^, $ 붙임 let result = reRegex.test(repeatNum);

 

Use Capture Groups to Search and Replace

let wrongText = "The sky is silver.";
let silverRegex = /silver/;
wrongText.replace(silverRegex, "blue");
// Returns "The sky is blue."

You can also access capture groups in the replacement string with dollar signs ($).

"Code Camp".replace(/(\w+)\s(\w+)/, '$2 $1');
// Returns "Camp Code"
 
 
 

 

 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/12   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
글 보관함