Regular Expressions Basics
Part of the Logic & Flow section of Coddy's Java journey — lesson 46 of 59.
Regular Expressions (regex) are patterns used to search and validate strings. In Java, we use the matches() method to check if a string matches a pattern.
Check if a string contains only digits:
String text = "12345";
boolean isMatch = text.matches("[0-9]+");After executing the above code, isMatch contains:
true
Check if a string contains only letters:
String text = "Hello";
boolean isMatch = text.matches("[a-zA-Z]+");After executing the above code, isMatch contains:
true
Challenge
EasyCreate a method named validateInput that takes two arguments:
- A String (
text) to validate - A String (
type) that specifies the validation type
The method should validate the text based on these types:
- "number": must contain only digits (0-9)
- "word": must contain only letters (a-z or A-Z)
- "email": must contain @ and at least one character before it
- "phone": must contain exactly 10 digits
Return messages should be:
- If text is null: return "Invalid input"
- If type is invalid: return "Invalid type"
- If validation passes: return "Valid"
- If validation fails: return "Invalid"
Cheat sheet
Regular Expressions (regex) are patterns used to search and validate strings. In Java, use the matches() method to check if a string matches a pattern.
Check if a string contains only digits:
String text = "12345";
boolean isMatch = text.matches("[0-9]+");Check if a string contains only letters:
String text = "Hello";
boolean isMatch = text.matches("[a-zA-Z]+");Common regex patterns:
[0-9]+- one or more digits[a-zA-Z]+- one or more letters[0-9]{10}- exactly 10 digits.+@.+- contains @ with at least one character before it
Try it yourself
import java.util.Scanner;
public class Main {
public static String validateInput(String text, String type) {
// Write your code here
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String text = scanner.nextLine();
String type = scanner.nextLine();
if (text.equals("null")) text = null;
System.out.println(validateInput(text, type));
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysMatrix Addition & SubstractionJagged Arrays3D Arrays And BeyondCommon 2D Array PatternsRecap - All About Arrays2HashMap Part 1
What is a HashMap?Declare a HashMapAccessing ValuesCheck If Key ExistsModifying DictionariesRecap - HashMap5HashSet Part 2
Math - Union of HashSetsMath - Intersection of HashSetMath - Set DifferenceMath - Symmetric DifferenceSubsets and SupersetsIterating Over Sets8Advanced String Operations
StringBuilder BasicsStringBuffer IntroductionRegular Expressions BasicsPattern Matching with RegexString TokenizerAdvanced String Formatting