티스토리 뷰
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 OR
operators 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 i
flag. (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 g
flag. (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 dot
and 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 hyphen
character: -
.
For example, to match lowercase letters a
through e
you 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 caret
character (^
) after the opening bracket and before the characters you do not want to match.
For example, /[^aeiou]/gi
matches 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.
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+/g
would 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 a
characters are not in a row - there is a b
between 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
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 lazy
matching. "titanic"
matched against the adjusted regex of /t[a-z]*?i/
returns ["ti"]
.
Match Beginning String Patterns
In an earlier challenge, you used the caret
character (^
) inside a character set
to create a negated character set
in the form [^thingsThatWillNotBeMatched]
. Outside of a character set
, the caret
is used to search for patterns at the beginning of strings. // ^[a-z]는 스트링 앞에서 알파벳 찾는 것, [^a-z]는 반대
Match Ending String Patterns
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
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
\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
Match Whitespace / Match Non-Whitespace
\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 spaceRegex = /\s/g;
whiteSpace.match(spaceRegex);
// Returns [" ", " "]
Specify Upper and Lower Number of Matches
a
appearing between 3
and 5
times 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
Check for All or None
let british = "colour";
let rainbowRegex= /colou?r/;
rainbowRegex.test(american); // Returns true
rainbowRegex.test(british); // Returns true
Positive and Negative Lookahead
A positive lookahead
will 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 lookahead
will 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
capture groups
. Parentheses, (
and )
, are used to find repeat substrings. You put the regex of the pattern that will repeat in between the parentheses.\
) and then a number. This number starts at 1 and increases with each additional capture group you use. An example would be \1
to match the first group.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);
capture groups
in reRegex
to 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"
'공부일지(TIL) > JavaScript' 카테고리의 다른 글
Prototype(프로토타입) (0) | 2019.03.14 |
---|---|
Object Oriented Programming: Inheritance(상속), Mixin, Closure, IIFE (0) | 2019.03.11 |
ES7, ES8 (0) | 2019.03.08 |
pass by reference, shallow copy (0) | 2019.03.08 |
Currying, Compose, Deterministic (0) | 2019.03.07 |
- Total
- Today
- Yesterday
- rxjs
- CSS
- Java
- Redux
- react
- c언어
- 개발 공부
- jQuery
- youtube data api
- GIT
- Data Structure
- Prefix Sums
- Session
- getter
- 제네릭스
- 자바
- 깃
- this
- 인스턴스
- til
- useEffect
- Conflict
- package.json
- oracle
- SQL
- 리덕스
- linkedlist
- 포인터 변수
- 알고리즘
- JavaScript
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |