diff --git a/src/main/java/BonusExercises.java b/src/main/java/BonusExercises.java index e9e486c..2e3679e 100644 --- a/src/main/java/BonusExercises.java +++ b/src/main/java/BonusExercises.java @@ -13,49 +13,60 @@ public class BonusExercises { return matcher.matches(); } - /* - This method should find and return the first date in a string. - - Supported formats: - - American: MM/DD/YYYY (e.g., 12/09/2023) - - British: DD/MM/YYYY (e.g., 12/09/2023 — same pattern, context matters) - - ISO: YYYY-MM-DD (e.g., 2024-07-15) - - Slash variant: YYYY/MM/DD (e.g., 2025/01/01) - - If no match for a date is found in the string, return null. - */ public String findDate(String string) { - // todo + if (string == null) {return null;} + String regex = "\\b(\\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])|\\d{4}/(0[1-9]|1[0-2])/(0[1-9]|[12][0-9]|3[01])|(0[1-9]|[12][0-9]|3[01])/(0[1-9]|1[0-2])/\\d{4})\\b"; + Pattern pattern = Pattern.compile(regex); + Matcher matcher = pattern.matcher(string); + if (matcher.find()) { + return matcher.group(); + } return null; } - /* - given a string, implement the method to detect all valid passwords - then, it should return the count of them - a valid password has the following properties: - - at least 8 characters - - has to include at least one uppercase letter, and at least a lowercase - - at least one number and at least a special char "!@#$%^&*" - - has no white-space in it - */ public int findValidPasswords(String string) { - // todo - return -1; + String regex = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[^A-Za-z0-9])\\S{8,}$"; + Pattern pattern = Pattern.compile(regex); + Matcher matcher = pattern.matcher(string); + String[] passwords = string.split(" "); + int count = 0; + for (String pass: passwords){ + if (pattern.matcher(pass).matches()){ + count++; + } + } + return count; } - - /* - you should return a list of *words* which are palindromic - by word we mean at least 3 letters with no whitespace in it - - note: your implementation should be case-insensitive, e.g. Aba -> is palindrome - */ + public List findPalindromes(String string) { List list = new ArrayList<>(); - // todo + String regex = "\\b[a-zA-Z]{3,}\\b"; + Pattern pattern = Pattern.compile(regex); + Matcher matcher = pattern.matcher(string); + while (matcher.find()) { + if (CheckPalindrome(matcher.group())) { + list.add(matcher.group()); + } + } return list; } + private boolean CheckPalindrome(String str) { + str = str.toLowerCase(); + int i = 0; + int j = str.length() - 1; + while (i < str.length() / 2 ) { + if (str.charAt(i) != str.charAt(j)) { + return false; + } + i++; + j--; + + } + return true; + } + public static void main(String[] args) { // you can test your code here }