返回

正则表达式教程:校验银行卡号

正则表达式

一、正则解释

正则表达式:/^[1-9]\d{9,29}$/

  • ^ :表示字符串开始
  • [1-9] :匹配 1 到 9 之间的数字,确保银行卡号首位非 0
  • \d :匹配数字
  • {9,29} :匹配 9 到 29 个数字,涵盖 10 到 30 位的银行卡号长度
  • $ :表示字符串结束

二、使用场景

此正则表达式可用于校验各种银行卡号,包括对公账户和私有账户,长度范围为 10 到 30 位。

三、代码示例

JavaScript

const bankCardNumberRegex = /^[1-9]\d{9,29}$/;

console.log(bankCardNumberRegex.test("6234567890")); // true
console.log(bankCardNumberRegex.test("6222026006705354000")); // true
console.log(bankCardNumberRegex.test("0123456789")); // false

Java

import java.util.regex.Pattern;

public class BankCardNumberValidator {
    public static void main(String[] args) {
        Pattern bankCardNumberPattern = Pattern.compile("^[1-9]\\d{9,29}
import java.util.regex.Pattern;

public class BankCardNumberValidator {
    public static void main(String[] args) {
        Pattern bankCardNumberPattern = Pattern.compile("^[1-9]\\d{9,29}$");

        System.out.println(bankCardNumberPattern.matcher("6234567890").matches()); // true
        System.out.println(bankCardNumberPattern.matcher("6222026006705354000").matches()); // true
        System.out.println(bankCardNumberPattern.matcher("0123456789").matches()); // false
    }
}
quot;); System.out.println(bankCardNumberPattern.matcher("6234567890").matches()); // true System.out.println(bankCardNumberPattern.matcher("6222026006705354000").matches()); // true System.out.println(bankCardNumberPattern.matcher("0123456789").matches()); // false } }

PHP

<?php
if (preg_match("/^[1-9]\d{9,29}$/", "6234567890")) {
    echo "Valid bank card number";
} else {
    echo "Invalid bank card number";
}
?>

Python

import re

bank_card_number_pattern = r"^[1-9]\d{9,29}
import re

bank_card_number_pattern = r"^[1-9]\d{9,29}$"

print(re.match(bank_card_number_pattern, "6234567890")) # <re.Match object; span=(0, 10), match='6234567890'>
print(re.match(bank_card_number_pattern, "6222026006705354000")) # <re.Match object; span=(0, 20), match='6222026006705354000'>
print(re.match(bank_card_number_pattern, "0123456789")) # None
quot;
print(re.match(bank_card_number_pattern, "6234567890")) # <re.Match object; span=(0, 10), match='6234567890'> print(re.match(bank_card_number_pattern, "6222026006705354000")) # <re.Match object; span=(0, 20), match='6222026006705354000'> print(re.match(bank_card_number_pattern, "0123456789")) # None