In this Java Regex Tutorial we want to learn about Java Regex Validation, Regular expressions is also known as regex, they are powerful tool for validating and manipulating text. You can use java regex to validate user input, extract data from a text file and many more. in this article we want to explore the basics of Java regex validation.
Java Regex Validation
For using regex in Java, we need to use java.util.regex package. this package provides different classes and methods for working with regex patterns. two most important classes in this package are Pattern and Matcher.
Pattern class represents a regex pattern. we can create a pattern by calling static method Pattern.compile(), and it takes a string argument that represents the regex pattern. for example if we want to validate a string that contains only letters and spaces we can use this pattern.
1 |
Pattern pattern = Pattern.compile("^[a-zA-Z ]+$"); |
This pattern matches any string that contains one or more letters or spaces. this ^ character represents the beginning of the string, and $ character represents the end of the string. [a-zA-Z ] part of the pattern matches any letter (upper or lowercase) or space character.
after that we have a pattern, we can use Matcher object to match the pattern against a string. we creates a Matcher by calling matcher() method on the pattern, and we need to pass the string we want to match against.
This is an example.
1 2 |
String input = "Codeloop.Org"; Matcher matcher = pattern.matcher(input); |
Now we can use Matcher methods to test if the input matches the pattern. most common method is matches() which returns true if the entire input matches the patter
1 2 3 4 5 |
if (matcher.matches()) { // Input is valid } else { // Input is invalid } |
We can also use find() method to search for the pattern inside the input. this method returns true if the pattern is found.
1 2 3 4 5 |
if (matcher.find()) { // Pattern is found } else { // Pattern is not found } |
These are some examples of common regex patterns:
Email validation | ^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4}$ |
Phone number validation | ^\\d{3}-\\d{3}-\\d{4}$ |
Date validation | (0?[1-9]|1[012])/(0?[1-9]|[12][0-9]|3[01])/(19|20)\\d\\d$ |
These patterns can be used to validate user input in different scenarios. for example we have a website and we want to validate the email address of users when they want to signup for our website, than for this we can use email validation pattern.
Java Regex Tutorial – Regex Syntax
Subscribe and Get Free Video Courses & Articles in your Email