返回
正则表达式教程:验证帐号是否合法
正则表达式
2024-02-28 16:01:29
一、正则解释
元字符/分组 | 含义 |
---|---|
^ | 匹配字符串的开头 |
[a-zA-Z] | 匹配一个字母(大小写) |
\w | 匹配一个字母、数字或下划线 |
{4,15} | 匹配长度为 4-15 的字符串 |
$ | 匹配字符串的结尾 |
二、使用场景
该正则表达式用于验证帐号是否满足以下要求:
- 以字母开头
- 允许 5-16 个字节
- 可包含字母、数字和下划线组合
三、代码示例
JavaScript
const pattern = /^[a-zA-Z]\w{4,15}$/;
const isValid = pattern.test("justin"); // true
const isValid = pattern.test("justin1989"); // true
const isValid = pattern.test("justin_666"); // true
const isValid = pattern.test("123abc"); // false
const isValid = pattern.test("justin abc"); // false
Java
import java.util.regex.Pattern;
public class AccountValidator {
private static final String PATTERN = "^[a-zA-Z]\\w{4,15}import java.util.regex.Pattern;
public class AccountValidator {
private static final String PATTERN = "^[a-zA-Z]\\w{4,15}$";
public static boolean isValid(String account) {
return Pattern.matches(PATTERN, account);
}
public static void main(String[] args) {
System.out.println(isValid("justin")); // true
System.out.println(isValid("justin1989")); // true
System.out.println(isValid("justin_666")); // true
System.out.println(isValid("123abc")); // false
System.out.println(isValid("justin abc")); // false
}
}
quot;;
public static boolean isValid(String account) {
return Pattern.matches(PATTERN, account);
}
public static void main(String[] args) {
System.out.println(isValid("justin")); // true
System.out.println(isValid("justin1989")); // true
System.out.println(isValid("justin_666")); // true
System.out.println(isValid("123abc")); // false
System.out.println(isValid("justin abc")); // false
}
}
PHP
<?php
$pattern = '/^[a-zA-Z]\w{4,15}$/';
if (preg_match($pattern, "justin")) {
echo "Valid account";
} else {
echo "Invalid account";
}
if (preg_match($pattern, "justin1989")) {
echo "Valid account";
} else {
echo "Invalid account";
}
if (preg_match($pattern, "justin_666")) {
echo "Valid account";
} else {
echo "Invalid account";
}
if (preg_match($pattern, "123abc")) {
echo "Valid account";
} else {
echo "Invalid account";
}
if (preg_match($pattern, "justin abc")) {
echo "Valid account";
} else {
echo "Invalid account";
}
Python
import re
pattern = r"^[a-zA-Z]\w{4,15}import re
pattern = r"^[a-zA-Z]\w{4,15}$"
print(re.match(pattern, "justin")) # True
print(re.match(pattern, "justin1989")) # True
print(re.match(pattern, "justin_666")) # True
print(re.match(pattern, "123abc")) # None
print(re.match(pattern, "justin abc")) # None
quot;
print(re.match(pattern, "justin")) # True
print(re.match(pattern, "justin1989")) # True
print(re.match(pattern, "justin_666")) # True
print(re.match(pattern, "123abc")) # None
print(re.match(pattern, "justin abc")) # None