Intro Common Regex
這篇介紹Common Regex,它是正則表示式,針對參數做基本檢核(禁止非法字元)。
Pattern Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| // UserId: 長度1 - 30 小寫英數混合,不允許特殊字元 private static final Pattern userIdPattern = Pattern.compile("^[0-9a-z]{1,30}$");
// Password: 長度6 - 12 字元,only English and number private static final Pattern passwordPattern = Pattern.compile("^[0-9a-zA-Z]{6,12}$");
// Url: start-http:// or https://,不允許特殊字元 private static final Pattern urlPattern = Pattern.compile( "^(http(s)?:\\/\\/)?(www.)?([a-zA-Z0-9])+([\\-\\.]{1}[a-zA-Z0-9]+)*\\.[a-zA-Z0-9]{2,5}(:[0-9]{1,5})?(\\/[^\\s]*)?$");
// telegram chat_id : 長度 1 - 100字元,允許數字和- private static final Pattern telegramChatIdPattern = Pattern.compile("^[-0-9]{1,100}$");
// telegram token : 長度 1 - 200,允許英(大小寫)數字、(:)、(-)、(_) private static final Pattern telegramTokenPattern = Pattern.compile("^[0-9a-zA-Z:$-/_]{1,200}$");
|
Implementation Example
1 2 3 4 5 6 7 8 9 10
| public static boolean isValidatedUserId(String value) { if (isEmpty(value)) { return false; } return isMatched(userIdPattern, value); //替換Pattern }
public static boolean isMatched(Pattern pattern, String value) { return pattern.matcher(value).matches(); }
|