验证手机号码是否正确

> Java 中使用正则表达式验证手机号码的方法

    
    	import java.util.regex.Matcher;
    	import java.util.regex.Pattern;
    
    	public class PhoneNumberValidator {
    		public static void main(String[] args) {
    			String phoneNumber1 = "15161596669";
    			String phoneNumber2 = "12345678901";
    
    			boolean isValid1 = validatePhoneNumber(phoneNumber1);
    			boolean isValid2 = validatePhoneNumber(phoneNumber2);
    
    			System.out.println(phoneNumber1 + " is valid: " + isValid1);
    			System.out.println(phoneNumber2 + " is valid: " + isValid2);
    		}
    
    		public static boolean validatePhoneNumber(String phoneNumber) {
    			// 定义手机号码的正则表达式,这里以常见的中国大陆手机号码格式为例
    			// 手机号码开头为 1,第二位可以是 3、4、5、6、7、8、9,后面跟着 9 位数字
    			String regex = "^1[3-9]\\d{9}$";
    			Pattern pattern = Pattern.compile(regex);
    			Matcher matcher = pattern.matcher(phoneNumber);
    			return matcher.matches();
    		}
    	}
    
    				

Java 中文转拼音

> Java 中可以使用第三方库pinyin4j来实现中文转拼音的功能


	import net.sourceforge.pinyin4j.PinyinHelper;
	import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
	import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
	import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
	import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

	public class ChineseToPinyin {
		public static void main(String[] args) {
			String chinese = "你好,世界";
			try {
				// 设置拼音输出格式
				HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
				format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
				format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);

				StringBuilder pinyin = new StringBuilder();
				for (char c : chinese.toCharArray()) {
					if (Character.toString(c).matches("[\\u4E00-\\u9FA5]")) {
						// 获取汉字的拼音字符串数组
						String[] pinyinArray = PinyinHelper.toPinyinArray(c, format);
						if (pinyinArray!= null) {
							pinyin.append(pinyinArray[0]);
						}
					} else {
						pinyin.append(c);
					}
				}
				System.out.println("中文转拼音:" + pinyin);
			} catch (BadHanyuPinyinOutputFormatCombination e) {
				e.printStackTrace();
			}
		}
	}