返回
正则表达式教程:统一社会信用代码(宽松匹配)
正则表达式
2024-02-28 15:47:48
一、正则解释
正则表达式:^(([0-9A-Za-z]{15})|([0-9A-Za-z]{18})|([0-9A-Za-z]{20}))$/
- ^: 正则表达式的开头
- $: 正则表达式的结尾
- (): 捕获组
- |: 逻辑或(匹配任何捕获组)
- [0-9A-Za-z]: 匹配数字或字母
- {15}: 匹配 15 个字符
- {18}: 匹配 18 个字符
- {20}: 匹配 20 个字符
二、使用场景
该正则表达式用于宽松匹配统一社会信用代码,包括 15 位、18 位和 20 位的数字和字母组合。
三、代码示例
JavaScript:
const regex = /^(([0-9A-Za-z]{15})|([0-9A-Za-z]{18})|([0-9A-Za-z]{20}))$/;
const codes = ['91110108772551611J', '911101085923662400'];
for (const code of codes) {
if (regex.test(code)) {
console.log(`${code} is a valid unified social credit code.`);
} else {
console.log(`${code} is not a valid unified social credit code.`);
}
}
Java:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class UnifiedSocialCreditCodeMatcher {
private static final String REGEX = "^(([0-9A-Za-z]{15})|([0-9A-Za-z]{18})|([0-9A-Za-z]{20}))import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class UnifiedSocialCreditCodeMatcher {
private static final String REGEX = "^(([0-9A-Za-z]{15})|([0-9A-Za-z]{18})|([0-9A-Za-z]{20}))$";
public static void main(String[] args) {
String[] codes = {"91110108772551611J", "911101085923662400"};
for (String code : codes) {
Pattern pattern = Pattern.compile(REGEX);
Matcher matcher = pattern.matcher(code);
if (matcher.matches()) {
System.out.println(code + " is a valid unified social credit code.");
} else {
System.out.println(code + " is not a valid unified social credit code.");
}
}
}
}
quot;;
public static void main(String[] args) {
String[] codes = {"91110108772551611J", "911101085923662400"};
for (String code : codes) {
Pattern pattern = Pattern.compile(REGEX);
Matcher matcher = pattern.matcher(code);
if (matcher.matches()) {
System.out.println(code + " is a valid unified social credit code.");
} else {
System.out.println(code + " is not a valid unified social credit code.");
}
}
}
}
PHP:
<?php
$regex = '/^(([0-9A-Za-z]{15})|([0-9A-Za-z]{18})|([0-9A-Za-z]{20}))$/';
$codes = ['91110108772551611J', '911101085923662400'];
foreach ($codes as $code) {
if (preg_match($regex, $code)) {
echo "$code is a valid unified social credit code.<br>";
} else {
echo "$code is not a valid unified social credit code.<br>";
}
}
?>
Python:
import re
regex = r'^(([0-9A-Za-z]{15})|([0-9A-Za-z]{18})|([0-9A-Za-z]{20}))import re
regex = r'^(([0-9A-Za-z]{15})|([0-9A-Za-z]{18})|([0-9A-Za-z]{20}))$'
codes = ['91110108772551611J', '911101085923662400']
for code in codes:
if re.match(regex, code):
print(f'{code} is a valid unified social credit code.')
else:
print(f'{code} is not a valid unified social credit code.')
#x27;
codes = ['91110108772551611J', '911101085923662400']
for code in codes:
if re.match(regex, code):
print(f'{code} is a valid unified social credit code.')
else:
print(f'{code} is not a valid unified social credit code.')