返回
正则表达式教程:英文姓名解析
正则表达式
2024-02-28 15:56:49
一、正则解释
正则表达式 /(^[a-zA-Z][a-zA-Z\s]{0,20}[a-zA-Z]$)/ 分为以下部分:
- ^: 表示字符串的开始。
- [a-zA-Z]: 匹配一个字母,可以是小写或大写。
- [a-zA-Z\s]{0,20}: 匹配由字母和空格组成的字符串,长度在 0 到 20 之间(不包括)。
- [a-zA-Z]: 匹配一个字母,可以是小写或大写。
- $: 表示字符串的结束。
二、使用场景
此正则表达式用于匹配英文姓名,它可以用于:
- 从文本中提取英文姓名
- 验证用户输入的姓名是否为英文格式
- 对姓名进行格式化或处理
三、代码示例
JavaScript
const regex = /(^[a-zA-Z][a-zA-Z\s]{0,20}[a-zA-Z]$)/;
const names = ['James', 'Kevin Wayne Durant', 'Dirk Nowitzki'];
for (let name of names) {
if (regex.test(name)) {
console.log(`${name} is a valid English name.`);
} else {
console.log(`${name} is not a valid English name.`);
}
}
Java
import java.util.regex.Pattern;
public class EnglishNameValidation {
public static void main(String[] args) {
String regex = "^[a-zA-Z][a-zA-Z\\s]{0,20}[a-zA-Z]import java.util.regex.Pattern;
public class EnglishNameValidation {
public static void main(String[] args) {
String regex = "^[a-zA-Z][a-zA-Z\\s]{0,20}[a-zA-Z]$";
String[] names = {"James", "Kevin Wayne Durant", "Dirk Nowitzki"};
for (String name : names) {
boolean isValid = Pattern.matches(regex, name);
System.out.println(name + " is " + (isValid ? "valid" : "invalid") + " English name.");
}
}
}
quot;;
String[] names = {"James", "Kevin Wayne Durant", "Dirk Nowitzki"};
for (String name : names) {
boolean isValid = Pattern.matches(regex, name);
System.out.println(name + " is " + (isValid ? "valid" : "invalid") + " English name.");
}
}
}
PHP
<?php
$regex = '/^[a-zA-Z][a-zA-Z\s]{0,20}[a-zA-Z]$/';
$names = ['James', 'Kevin Wayne Durant', 'Dirk Nowitzki'];
foreach ($names as $name) {
if (preg_match($regex, $name)) {
echo "$name is a valid English name.<br>";
} else {
echo "$name is not a valid English name.<br>";
}
}
Python
import re
regex = r"^[a-zA-Z][a-zA-Z\s]{0,20}[a-zA-Z]import re
regex = r"^[a-zA-Z][a-zA-Z\s]{0,20}[a-zA-Z]$"
names = ['James', 'Kevin Wayne Durant', 'Dirk Nowitzki']
for name in names:
if re.match(regex, name):
print(f"{name} is a valid English name.")
else:
print(f"{name} is not a valid English name.")
quot;
names = ['James', 'Kevin Wayne Durant', 'Dirk Nowitzki']
for name in names:
if re.match(regex, name):
print(f"{name} is a valid English name.")
else:
print(f"{name} is not a valid English name.")