Regex is something very old and widely used today everywhere. It's an airtight security feature that helps you keep your database clean and saves the response time of the server when attached to frontend fields. They can surely seem intimidating at first, but understanding them will be a cakewalk by the end of this article. This article explains Regex from scratch. We'll also test some patterns directly and by the end create a simple form with regex validations on the frontend.
正则表达式是非常古老的东西,如今已在世界各地广泛使用。 这是一种密封的安全功能,可以帮助您保持数据库的清洁,并在连接到前端字段时节省服务器的响应时间。 乍一看,它们肯定看上去很吓人,但到本文结尾,理解它们将是一个轻而易举的事。 本文从头开始解释正则表达式。 我们还将直接测试一些模式,最后创建一个带有前端正则表达式验证的简单表单。
Okay, so what exactly are regular expressions?
好的, 正则表达式到底是什么?
They are expressions that help us check a series of characters for some 'matches'. Let's say you have an email id, it follows a certain pattern. For example, it has an '@' symbol and ends in a .com or .in extension. These patterns are what regex is used for. They are widely used in a lot of programming and database languages as well. They begin with '/' and end in '/' which means anything inside / / is a regular expression. So we have a basic syntax,
它们是可以帮助我们检查一系列字符是否匹配的表达式。 假设您有一个电子邮件ID,它遵循某种模式。 例如,它带有一个'@'符号,并以.com或.in扩展名结尾。 这些模式是正则表达式的用途。 它们也广泛用于许多编程和数据库语言中。 他们开始以“/”和结束“/”,这意味着什么内部/ /正则表达式 。 所以我们有一个基本的语法,
/ regex pattern /
元字符 (Metacharacters)
We use metacharacters to validate expressions. These characters have some special meaning in the regex. Some of them are,
我们使用元字符来验证表达式 。 这些字符在正则表达式中有一些特殊含义。 他们之中有一些是,
Format | Description |
---|---|
\d | Match any digit characters between 0-9 |
\w | Match any word character which includes a-z, A-Z, 0-9 and spaces |
\s | Match a whitespace character (spaces, tabs etc) |
\t | Match a tab character |
d-- | Matches the literal character 'd' |
\d-- | Matches any digit character |
格式 | 描述 |
---|---|
\ d | 匹配0-9之间的任何数字字符 |
\ w | 匹配包括az,AZ,0-9和空格的任何单词字符 |
\ s | 匹配空白字符(空格,制表符等) |
\ t | 匹配制表符 |
d-- | 匹配文字字符“ d” |
\ d-- | 匹配任何数字字符 |
特殊的角色 (Special Characters)
We also have some special characters for some special matches,
我们还为一些特殊比赛提供了一些特殊字符,
Format | Description |
---|---|
+ | One or more quantifier |
\ | The escape character |
[ ] | The character set |
[ ^ ] | The negate symbol in a character set |
? | Zero or one quantifier (Makes a preceding character optional) |
. | Any character barring the newline character |
* | Zero or more quantifier |
格式 | 描述 |
---|---|
+ | 一个或多个量词 |
\ | 转义符 |
[] | 字符集 |
[^] | 字符集中的取反符号 |
? | 零或一个量词(使前面的字符可选) |
。 | 禁止换行符的任何字符 |
* | 零个或多个量词 |
General Syntax
一般语法
We have already seen that our regular expression must lie between / /. The ^ symbol at the start means that our string must start with the character immediately after ^ and $ indicates the end of the string. Hence our general syntax for any regular expression becomes,
我们已经看到我们的正则表达式必须位于/ /之间。 开头的^符号表示我们的字符串必须以^之后的字符开头,而$表示字符串的结尾。 因此,我们对任何正则表达式的通用语法变为:
/^ regex pattern $/
Alright now let's set up a form where we will add validations. If you're unfamiliar with forms and submit events in JavaScript, have a quick read here,
好了,现在让我们建立一个表单,在其中添加验证。 如果您不熟悉表单并使用JavaScript提交事件,请在此处快速阅读,
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Forms</title>
</head>
<style>
form {
margin: 20px auto;
padding: 20px 20px;
text-align: center;
width: 400px;
height: 400px;
background: rgba(111, 146, 44, 0.514);
}
h2 {
font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
font-size: 40px;
color: white;
}
input {
background: white;
border: 2px solid gainsboro;
height: 30px;
padding: 10px auto;
margin: 10px auto;
text-align: center;
}
input::placeholder {
color: rgba(66, 151, 63, 0.61);
text-transform: uppercase;
letter-spacing: 3px;
text-align: center;
}
input[type=submit] {
border: 2px solid gainsboro;
border-radius: 8px;
cursor: pointer;
background-color: rgb(97, 179, 138);
color: whitesmoke;
padding: 5px 5px;
margin: 10px;
text-transform: uppercase;
box-shadow: 1px 1px 1px rgb(229, 233, 236);
}
</style>
<body>
<form action="">
<h2>Form</h2>
<input type="text" id="userName" placeholder="User Name">
<br>
<input type="email" id="Email" placeholder="Email">
<br>
<input type="password" id="password" placeholder="Password">
<br>
<input type="submit">
</form>
</body>
We now have a basic form set up with three fields: user name, email and password. Should look something like this,
现在,我们有了一个基本表单,其中包含三个字段: 用户名 , 电子邮件和密码 。 应该看起来像这样
![regular expression | example 1](https://i-blog.csdnimg.cn/blog_migrate/0547257566ac376bb23cf6d4c02157c1.png)
Let's first try to figure out a simple regex pattern for each.
让我们首先尝试为每种方法找出一个简单的正则表达式模式 。
Let's say the username must have lowercase letters only and should be at least 6 letters long.
假设用户名只能包含小写字母,并且至少应包含6个字母。
The regex pattern for the username will be: /^[a-z]{6,}$/.
用户名的正则表达式模式为:/ ^ [az] {6,} $ / 。
The character set indicates that the user name must contain only those characters between a-z and the braces with {6,} indicates that it must be at least 6 characters long. Since the upper bound is not specified, we can have any number of characters as long as they're more than 6 characters long.
字符集表示用户名必须仅包含az和大括号之间的那些字符,并带有{6,},表示该用户名长度必须至少为6个字符。 由于未指定上限,因此我们可以使用任意数量的字符,只要它们的长度超过6个字符即可。
Let's figure out the pattern for email. We want the user to enter an email with an '@' symbol somewhere in between the email and should only end in a valid extension like .com, in, uk. A dot and anything after that can be an extension.
让我们找出电子邮件的模式。 我们希望用户在电子邮件之间的某处输入带有'@'符号的电子邮件,并且只能以.com,in,uk等有效扩展名结尾。 点和其后的任何内容都可以作为扩展。
So the pattern for our email is: /^[^@][email protected][^\.]+\..+$/
因此,我们的电子邮件格式为:/ ^ [^ @] [受电子邮件保护] [^ \。] + \ .. + $ /
We begin with anything but the '@' since our email must not begin with an @, then check for the '@' then we negate the '.' since we must have some domain name before our extension begins. The \ in between the regex is used to escape the sequence if it isn't a metacharacter or a special character.
我们以“ @”开头,因为我们的电子邮件不能以@开头,然后检查“ @”,然后取反“。”。 因为我们的扩展名开始前必须有一些域名。 如果不是元字符或特殊字符, 则使用正则表达式之间的\来转义该序列。
Finally, let's break down the regex for the password. Our password should be between 8 to 15 characters long and must contain at least one uppercase, one lowercase, and one numeric digit.
最后,让我们分解一下密码的正则表达式。 我们的密码长度应介于8到15个字符之间,并且必须至少包含一个大写字母,一个小写字母和一个数字。
Pattern for password: /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,15}$/
密码的模式:/^(?=.*\d)(?=.*[az])(?=.*[AZ]).{8,15}$/
The () evaluates regex searches separately so we can break down the pattern into 3 parts.
()分别评估正则表达式搜索,因此我们可以将模式分为3部分。
(?=.*\d) implies that the string must contain at least one numeric digit, (?=.*[a-z]) implies that the string must contain at least one lowercase character and (?=.*[A-Z]) denotes that the string must contain at least one uppercase character.
(?=。* \ d)表示字符串必须至少包含一个数字, (?=。* [az])表示字符串必须至少包含一个小写字符,而(?=。* [AZ])表示字符串必须至少包含一个大写字符。
Alright, now we are done with the regex patterns. Let's see how we will implement validations using these in JavaScript.
好了,现在我们完成了正则表达式模式。 让我们看看如何在JavaScript中使用验证来实现验证。
HTML模式 (HTML Pattern)
The first method is to include the regex in the pattern attribute of our HTML tags of input fields. Here, we can use the inbuilt HTML pattern validation,
第一种方法是将正则表达式包含在我们输入字段HTML标签的pattern属性中。 在这里,我们可以使用内置HTML模式验证,
<form action="">
<h2>Form</h2>
<input type="text" pattern="/^[a-z]{6,}$/" id="userName" placeholder="User Name">
<br>
<input type="email" id="Email" pattern="/^[^@][email protected][^\.]+\..+$/" placeholder="Email">
<br>
<input type="password" id="password" pattern=" /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,15}$/" placeholder="Password">
<br>
<input type="submit">
</form>
Let's do it the other way now. Let's capture the patterns somewhere and check each input field if they match the pattern.
现在让我们做另一种方式。 让我们在某个位置捕获模式,并检查每个输入字段是否与模式匹配。
If we don't get a match we will append an error text to our HTML. For this, add the following to the styles,
如果没有找到匹配项,我们会将错误文本附加到我们HTML中。 为此,请在样式中添加以下内容,
.validationMsg {
color: brown;
font-size: 12px;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif
}
And include a p tag with a class validationMsg after the submit button in the form.
并在表单中的“提交”按钮之后添加一个带有类validateMsg的p标记。
<p class="validationMsg"></p>
Now we'll do the matching in our submit event.
现在,我们将在Submit事件中进行匹配。
<script>
const form=document.querySelector('form');
const msg=document.querySelector('.validationMsg');
form.addEventListener('submit',e=>{
const usernamePattern=/^[a-z]{6,}$/;
const emailPattern=/^[^@]+@[^\.]+\..+$/;
const passwordPattern=/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,15}$/;
e.preventDefault();
if(!usernamePattern.test(form.userName.value)){
msg.innerHTML+='Username must be at least 6 characters long all lowercase <br/>';
}
if(!emailPattern.test(form.Email.value)){
msg.innerHTML+='Please enter a valid email <br/>'
}
if(!passwordPattern.test(form.password.value)){
msg.innerHTML+='Password must contain at least one uppercase, one lowercase and one numeric value and must be 8 to 15 characters long <br/>'
}
})
</script>
We capture the form and the validation message to a variable. We store our regex patterns in different variables for every input field check if the pattern matches what the user typed in the field. If it does, we do nothing (maybe we get a response from the backend that reroutes the page) and if it doesn't, we show the error text underneath the submit button inside the form itself.
我们将表单和验证消息捕获到一个变量中。 对于每个输入字段,我们将正则表达式模式存储在不同的变量中,检查该模式是否与用户在该字段中键入的内容匹配。 如果是这样,我们什么也不做(也许我们从后端重新路由页面得到响应),如果没有,我们将在表单本身内部的“提交”按钮下方显示错误文本。
![regular expression | example 2](https://i-blog.csdnimg.cn/blog_migrate/5980c4ac8d0467c8329139dbac2b1d04.png)
Great! Our validations work fine. Test them out further with various combinations. You can refer to the full code here,
大! 我们的验证工作正常。 使用各种组合进一步测试它们。 您可以在此处参考完整的代码,
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Forms</title>
</head>
<style>
form {
margin: 20px auto;
padding: 20px 20px;
text-align: center;
width: 400px;
height: 400px;
background: rgba(111, 146, 44, 0.514);
}
h2 {
font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
font-size: 40px;
color: white;
}
input {
background: white;
border: 2px solid gainsboro;
height: 30px;
padding: 10px auto;
margin: 10px auto;
text-align: center;
}
input::placeholder {
color: rgba(66, 151, 63, 0.61);
text-transform: uppercase;
letter-spacing: 3px;
text-align: center;
}
input[type=submit] {
border: 2px solid gainsboro;
border-radius: 8px;
cursor: pointer;
background-color: rgb(97, 179, 138);
color: whitesmoke;
padding: 5px 5px;
margin: 10px;
text-transform: uppercase;
box-shadow: 1px 1px 1px rgb(229, 233, 236);
}
.validationMsg {
color: brown;
font-size: 12px;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif
}
</style>
<body>
<form action="">
<h2>Form</h2>
<!-- <span style="color:fuchsia;font-size:10px">Username must be at least 6 characters long with nly lowercase cahracters</span> -->
<input type="text" id="userName" placeholder="User Name">
<br>
<input type="email" id="Email" placeholder="Email">
<br>
<input type="password" id="password" placeholder="Password">
<br>
<input type="submit">
<p class="validationMsg"></p>
</form>
</body>
<script>
const form = document.querySelector('form');
const msg = document.querySelector('.validationMsg');
form.addEventListener('submit', e => {
const usernamePattern = /^[a-z]{6,}$/;
const emailPattern = /^[^@]+@[^\.]+\..+$/;
const passwordPattern = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,15}$/;
e.preventDefault();
if (!usernamePattern.test(form.userName.value)) {
msg.innerHTML += 'Username must be at least 6 characters long all lowercase <br/>';
}
if (!emailPattern.test(form.Email.value)) {
msg.innerHTML += 'Please enter a valid email <br/>'
}
if (!passwordPattern.test(form.password.value)) {
msg.innerHTML += 'Password must contain at least one uppercase, one lowercase and one numeric value and must be 8 to 15 characters long <br/>'
}
})
</script>
</html>
翻译自: https://www.includehelp.com/code-snippets/regular-expressions-in-javascript.aspx