3 回答

TA貢獻1830條經(jīng)驗 獲得超3個贊
允許使用簡單的郵政編碼(例如 12345)并強制規(guī)定,如果找到可接受的分隔符(空格、逗號、管道),它必須以四位數(shù)字結尾,這個正則表達式就足夠了。
[0-9]{5}(?:[-,| ][0-9]{4})?

TA貢獻1794條經(jīng)驗 獲得超8個贊
我不知道您所在國家/地區(qū)的確切郵政編碼規(guī)則,但此代碼段將幫助您入門:
// 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");
}

TA貢獻1829條經(jīng)驗 獲得超4個贊
您不需要負前瞻,您可以使用字符類 ( []
) 代替|
運算符,并且您希望使用^
和$
來表示字符串的開頭和結尾。像這樣:
"34343-1232".matches("^[0-9| -]+$")
添加回答
舉報