Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 30 additions & 31 deletions AP1403 - RegEx/src/main/java/Exercises.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,55 +5,54 @@

public class Exercises {

/*
complete the method below, so it will validate an email address
*/
public boolean validateEmail(String email) {
String regex = ""; // todo
String regex = "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(email);

return matcher.matches();
}

/*
this method should find a date in string
note that it should be in british or american format
if there's no match for a date, return null
*/
public String findDate(String string) {
// todo
String regex = "(0[1-9]|[12][0-9]|3[01])[-/](0[1-9]|1[0-2])[-/](19|20)\\d\\d|\\d{4}[-/](0[1-9]|1[0-2])[-/](0[1-9]|[12][0-9]|3[01])";
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)(?=.*[!@#$%^&*])[^\\s]{8,}";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(string);
int count = 0;
while (matcher.find()) {
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<String> findPalindromes(String string) {
List<String> list = new ArrayList<>();
// todo
String[] words = string.split("\\W+");
for (String word : words) {
if (word.length() >= 3) {
String lowerWord = word.toLowerCase();
String reversed = new StringBuilder(lowerWord).reverse().toString();
if (lowerWord.equals(reversed)) {
list.add(word);
}
}
}
return list;
}

public static void main(String[] args) {
// you can test your code here
Exercises exercises = new Exercises();
System.out.println(exercises.validateEmail("test@example.com"));
System.out.println(exercises.findDate("Today's date is 12/04/2025."));
System.out.println(exercises.findValidPasswords("Password1! and 1234Pass@ are valid."));
System.out.println(exercises.findPalindromes("Madam, this is a level example."));
}
}