gpt4 book ai didi

java - 可以包含字母数字字符但不能包含 | 以外的任何内容的正则表达式, - 和空间

转载 作者:行者123 更新时间:2023-12-01 16:45:31 25 4
gpt4 key购买 nike

验证邮政编码时,我试图检查邮政编码是否可以包含字母数字且只能包含字符 -|(空格)。

我正在检查

"34343-1232".matches("(?!|| |-|[0-9])"))

但这不起作用。有没有最佳方法来做到这一点?

最佳答案

我不知道您所在国家/地区的确切邮政编码规则,但此代码段将帮助您入门:

// define the pattern - should be defined as class field
// instead of + you could use {3,5} to match min. 3, max. 5 characters - see regular expressions manual
private static final Pattern PATTERN_ZIP = Pattern.compile("^[0-9A-Z]+[ \\-\\|]?[0-9A-Z]+$");

String zip = "1A2-3B4C5";
// Optional: let's make some text cleaning
String cleanZip = zip.toUpperCase().trim();

// Do the mat(c)h
Matcher m = PATTERN_ZIP.matcher(cleanZip);

if (m.find()) {
System.out.println("Zip code correct");
} else {
System.out.println("Zip code incorrect");
}

关于java - 可以包含字母数字字符但不能包含 | 以外的任何内容的正则表达式, - 和空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52284886/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com