使用正则表达式检验手机号是否合法
时间: 2023-11-22 12:50:23 浏览: 96
使用正则表达式检验手机号是否合法的方法如下:
1. JavaScript示例:
```javascript
function validatePhoneNumber(phoneNumber) {
var regex = /^1[3-9]\d{9}$/;
return regex.test(phoneNumber);
}
var phoneNumber1 = "13812345678";
var phoneNumber2 = "12345678901";
console.log(validatePhoneNumber(phoneNumber1)); // 输出:true
console.log(validatePhoneNumber(phoneNumber2)); // 输出:false
```
2. PHP示例:
```php
function validatePhoneNumber($phoneNumber) {
$regex = '/^1[3-9]\d{9}$/';
return preg_match($regex, $phoneNumber);
}
$phoneNumber1 = "13812345678";
$phoneNumber2 = "12345678901";
echo validatePhoneNumber($phoneNumber1); // 输出:1
echo validatePhoneNumber($phoneNumber2); // 输出:0
```
3. Java示例:
```java
public class PhoneNumberValidator {
public static void main(String[] args) {
String phoneNumber1 = "13812345678";
String phoneNumber2 = "12345678901";
System.out.println(validatePhoneNumber(phoneNumber1)); // 输出:true
System.out.println(validatePhoneNumber(phoneNumber2)); // 输出:false
}
public static boolean validatePhoneNumber(String phoneNumber) {
String regex = "^1[3-9]\\d{9}$";
return phoneNumber.matches(regex);
}
}
```
阅读全文