返回
正则表达式教程:验证大写英文字母
前端
2024-02-28 16:10:23
一、正则解释
正则表达式 /^[A-Z]+$/ 表示:
- ^ :匹配字符串的开头。
- [A-Z] :匹配大写英文字母 A 到 Z。
- + :匹配一个或多个前一个元素(即大写英文字母)。
- $ :匹配字符串的结尾。
整个正则表达式表示字符串必须以大写英文字母开头,只包含大写英文字母,并以大写英文字母结尾。
二、使用场景
这个正则表达式通常用于验证用户输入的密码、用户名或其他需要仅包含大写英文字母的字段。它有助于确保输入数据的有效性和安全性。
三、代码示例
JavaScript
const regex = /^[A-Z]+$/;
console.log(regex.test("ABC")); // true
console.log(regex.test("Kd")); // false
Java
import java.util.regex.Pattern;
public class RegexDemo {
public static void main(String[] args) {
String pattern = "^[A-Z]+import java.util.regex.Pattern;
public class RegexDemo {
public static void main(String[] args) {
String pattern = "^[A-Z]+$";
boolean isMatch = Pattern.matches(pattern, "ABC");
System.out.println(isMatch); // true
isMatch = Pattern.matches(pattern, "Kd");
System.out.println(isMatch); // false
}
}
quot;;
boolean isMatch = Pattern.matches(pattern, "ABC");
System.out.println(isMatch); // true
isMatch = Pattern.matches(pattern, "Kd");
System.out.println(isMatch); // false
}
}
PHP
$pattern = "/^[A-Z]+$/";
$result = preg_match($pattern, "ABC");
echo $result; // 1 (匹配成功)
$result = preg_match($pattern, "Kd");
echo $result; // 0 (匹配失败)
Python
import re
pattern = r"^[A-Z]+import re
pattern = r"^[A-Z]+$"
match = re.match(pattern, "ABC")
print(match) # <re.Match object; span=(0, 3), match='ABC'>
match = re.match(pattern, "Kd")
print(match) # None (不匹配)
quot;
match = re.match(pattern, "ABC")
print(match) # <re.Match object; span=(0, 3), match='ABC'>
match = re.match(pattern, "Kd")
print(match) # None (不匹配)