Welcome back to series about Regular expression in JavaScript. If you like this topic, this link for you follows another blog about this topic.Series about regex in JavaScript.
In this
article, we discuss about how to write shorthand pattern and another pattern in
Regular expression.
Table of
content:
- Use bracket “[]”
- Match first of the string
- Match end of the string
- Match characters [a-zA-Z0-9] – Shorthand
- Match no characters [a-zA-Z0-9]
- Match all number
- Match no number
- Match with length of word
- Practical application
Let’s go to
the content!
Use
bracket “[]”
In a
previous article, we came across some patterns that contain “[]”. Now, we will
discuss in more detail about the "[]" sign. Patterns containing “[]”
will return every letter and (not) find characters in this bracket “[]”.
let str = 'Hello world'
let regex = /[lo]/ig
let resultMatch = str.match(regex)
console.log(resultMatch)
// => Array [ "l", "l",
"o", "o", "l" ]
As shown,
the result will return every letter, character and (not) find characters in
this bracket “[]”.
Match
first of the string
Let’s look
at example below:
let str1 = 'abc'
let str2 = 'ebc'
let str3 = 'ibc'
let str4 = 'obc'
let str5 = 'ubc'
let regex = /^[ai]/ig
console.log(regex.test(str1)) // => true
console.log(regex.test(str2)) // => false
console.log(regex.test(str3)) // => true
console.log(regex.test(str4)) // => false
console.log(regex.test(str5)) // => false
You can see
that we have a pattern of "^" and "[]". We will analyze
this pattern as follows: the letters contained in the bracket "[]"
appear at the beginning of the string, the result will be true. So, if we don't
check every letter or character, we check if a word appears first or not, how
do we do it? Let's look at the example:
let str1 = "abc123xyz"
let str2 = "xyz123abc"
let str3 = "abcxyz123"
let str4 = "123abcxyz"
let regex = /^abc/ig
console.log(regex.test(str1)) // => true
console.log(regex.test(str2)) // => false
console.log(regex.test(str3)) // => true
console.log(regex.test(str4)) // => false
We have the
same pattern as in the previous example, but this time we don't use bracket
"[]", this means that words that start with the phrase
"abc" will return true results.
Now you have
a better understanding of how to use bracket “[]”. Depending on the purpose of
use, you choose accordingly.
Match end
of the string
For ending
in any letter, character or word, we add a "$" and at the end in the
pattern of the regex. Let's take a look at specific examples:
let str1 = "abc123xyz"
let str2 = "xyz123abc"
let str3 = "abcxyz123"
let str4 = "123abcxyz"
let regex = /xyz$/ig
console.log(regex.test(str1)) // => true
console.log(regex.test(str2)) // => false
console.log(regex.test(str3)) // => false
console.log(regex.test(str4)) // => true
Like the
usage of match first of the string. We put the "$" sign at the end of
the letter, character, word that we want to appear at the end. As the example
above, we require words that appear "xyz" at the end and words that
meet this pattern will return true, the rest will be false.
Match characters [a-zA-Z0-9] – Shorthand
In previous
articles, when we searched for letters from a - z, from A - Z or from 0 - 9 we
had the pattern [a-zA-Z0-9]. This way of writing is quite long, we have a more
concise way of writing it, which is to use "/w". When there is
"/w", we will understand that the letters to search for have a range
from a - z, A - Z and 0 - 9. Let's go to an example:
let str = '123 !@#% abc XYZ'
let normalRegex = /[a-zA-Z0-9]/g
let shorthandRegex = /\w/g
let normalResult = str.match(normalRegex)
let shorthandResult = str.match(shorthandRegex)
console.log(normalResult)
// => Array [ "1", "2",
"3", "a", "b", "c", "X",
"Y", "Z" ]
console.log(shorthandResult)
// => Array [ "1", "2",
"3", "a", "b", "c", "X",
"Y", "Z" ]
In the
string we have numbers, special characters, lowercase letters, uppercase
letters, and space. We use two patterns, “[a-zA-Z0-9]” and “[\w]” both return
the same result. Later if you need to search for letters or characters in this
range. You might consider using the pattern “\w”.
Match no
characters [a-zA-Z0-9]
In the
previous section, we had "\w" match the characters in the range
[a-zA-Z0-9]. If in case we want to find chacracters that are not in this range,
how will we do it?
let str = '123 !@#% abc XYZ'
let normalRegex = /[^a-zA-Z0-9]/g
let shorthandRegex = /\W/g
let normalResult = str.match(normalRegex)
let shorthandResult = str.match(shorthandRegex)
console.log(normalResult)
// => Array [ " ", "!",
"@", "#", "%", " ", " " ]
console.log(shorthandResult)
// => Array [ " ", "!",
"@", "#", "%", " ", " " ]
Do you
remember in the previous post? If we put the "^" in the bracket
"[]" and put it in the first position, the pattern will be
interpreted as not taking any characters contained in that pattern. Besides, we
have a more concise way of writing that is “/\W/” and remember that “W” will be
uppercase. In the example above, special characters and spaces are accepted,
while letters and characters in the range 0-9, a-z, and A-Z are ignored.
You have
many ways of dealing with the same problem. Please consider depending on each
specific requirements and conditions to use accordingly.
Match all
number
To search
for characters that are numbers, usually we will have that way
"[0-9]". Now we have a more concise way to use "\d".
let str = '123 !@#% abc XYZ'
let normalRegex = /[0-9]/g
let shorthandRegex = /\d/g
let normalResult = str.match(normalRegex)
let shorthandResult = str.match(shorthandRegex)
console.log(normalResult)
// => Array [ "1", "2",
"3" ]
console.log(shorthandResult)
// => Array [ "1", "2",
"3" ]
Both give similar results. So, you have a more concise way to search for characters that are numbers than using "\d".
Match no
number
Like the
above samples, we will also have a search for characters that are not numbers.
To use this pattern, we will use the pattern “\D”.
let str = '123 !% ac XZ'
let normalRegex = /[^0-9]/g
let shorthandRegex = /\D/g
let normalResult = str.match(normalRegex)
let shorthandResult = str.match(shorthandRegex)
console.log(normalResult)
// => Array [ " ", "!",
"%", " ", "a", "c", " ",
"X", "Z" ]
console.log(shorthandResult)
// => Array [ " ", "!",
"%", " ", "a", "c", " ",
"X", "Z" ]
You can see
that “[^0-9]” and “\D” are similar. And “\D” has a shorter spelling. Please use
and according to the appropriate situation.
Match
with length of word
When you
want the length of a word to be within a pre-specified range, or at least how
many characters will be contained in that word. Let's look at the example:
let str = 'aaa a aaaaa aaaaaa'
let regex = /a{2,4}/ig
let resultMatch = str.match(regex)
console.log(resultMatch)
// => Array(4) [ "aaa",
"aaaa", "aaaa", "aa" ]
With the
pattern "a{2, 4}", we will take the word with the letter
"a" repeated at least twice and at most 4 times. You can see that the
word "a" will not be included in the returned results. And the word
"aaaaaa" will only be taken "aaaa". This is the limit we
set initially. So if we just want the minimum number of iterations, and as long
as we want, we will have the following pattern:
let str = "Your time is limited,
so don't waste it living someone else's life. Don't be trapped by dogma – which
is living with the results of other people's thinking. -Steve Jobs"
let regex = /[a-z]{6,}/g
let resultMatch = str.match(regex)
console.log(resultMatch)
// => Array [ "limited",
"living", "someone", "trapped",
"living", "results", "people",
"thinking" ]
We can take
the pattern “{number, number}” and the character immediately preceding it will
determine the degree of repetition. In the above example, we only take words with
a length of 6.
Practical
application
We will go
into a practical example to apply all the knowledge above. You will create a
registration system for users. Users who want to create a username must meet
the following requirements: If there are numbers, they must be at the end.
Letters can be lowercase and uppercase. At least six characters long.
Six-letter names can't have numbers.
Let's go
into the analysis of the problem. We have, if there are numbers, they must be
at the end. That is, whether there is a number in the username or not is not
required, but when the number appears, it can only be at the end. We will have
the following pattern “\d*&”. "\d" refers to the object of
numbers, the "*" will be the beginning at zero, and the
"&" will be the numbers that will appear at the end.
Next, we
have a username that starts with letter and can be uppercase and lowercase. We
will use the pattern like this: “^[a-zA-Z]”. We have “[a-zA-Z]” which will
include the letters lowercase and uppercase from a to z. You will wonder why we
don't use "\w". Very good question, do you remember that
"\w" will also take the number from 0 to 9. That will not be true to
our requirements. And the "^" right at the beginning to ensure that
the letters will appear at the beginning.
Finally we
have at least six characters long. Six-letter names can't have numbers. We will
add “{6,}” after “[a-zA-Z]”. So we have just created the pattern that responds
to the request. Now let's use it to see how it all works.
let username1 = 'abcder123'
let username2 = 'Ab12der123'
let username3 = '123bcder'
let username4 = 'ASDFASDCXZxzcas'
let username5 = 'user5'
let username6 = 'user@#$%1'
let regex = /^[a-zA-Z]{6,}\d*$/g
console.log(regex.test(username1)) //
=> true
console.log(regex.test(username2)) //
=> false
console.log(regex.test(username3)) //
=> false
console.log(regex.test(username4)) //
=> true
console.log(regex.test(username5)) //
=> false
console.log(regex.test(username6)) //
=> false
Awesome!
Pattern works very well in identifying usernames that meet the requirements.
Conclusion
We've just
gone over new patterns and how to write shorthands for long patterns. And let's
go through solving a real problem about username.
If you have
any ideas, feel free to comments below. Thank you for joining with me. Have a
good day!
0 Nhận xét