In this post, we will how to match character using regex in java.
Table of Contents
Quick Solution for regex match any character in java
If you are looking for quick solution, you can use .
character to match any character. If you need to match set of characters, then you can use .*
.
Pattern | Description |
---|---|
"." | Matches single character ("." will match with single character String such as "A","B","$" etc) |
".*" | Matches any numbers of characters("." will match with single character String such as "AB","BQQQ","$AQ" etc) |
"X.Y" | Matches any character at 2nd position and String of length 3 should start with X and end with Y("X.Y" will match for String such as "XAY","XRY", "X#Y" etc) |
"X.*Y" | Matches String which Starts with X and ends with Y.("X.*Y" will match for String such as "XA2SY","X5$DY", "XOO9AY" etc) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
package org.arpit.java2blog; import java.util.regex.Pattern; public class RegexMatch { public static void main(String[] args) { // Match single character System.out.println((MatchCustomRegex("abc", "a.c") ? ("MATCH") : ("NOT MATCH"))); System.out.println((MatchCustomRegex("abkoc", "a.c") ? ("MATCH") : ("NOT MATCH"))); // Match multiple characters System.out.println((MatchCustomRegex("abkoc", "a.*c") ? ("MATCH") : ("NOT MATCH"))); } /** * Matches using a specific regex * @param MyInput * @param RegEx * @return */ public static boolean MatchCustomRegex(String MyInput, String RegEx) { // Attempt to match by using the regex (custom) // returns false if match failed Pattern pattern = Pattern.compile(RegEx); Matcher matcher = pattern.matcher(MyInput); return matcher.matches(); } } |
Output:
NOT MATCH
MATCH
Let’s deep dive into more about regex classes Pattern
and Matcher
.
Further reading:
Introduction
Java utility package tool regex (regular expression)
is often used among a vast variety of character match/search procedures, which it has two fundamental classes.
The first is the Pattern class
, used to process search and locate conventional expressions. Secondly, the Matcher
class is to identify any search for a defined pattern or sequence. The objective of this java utility package is to perform a search and replace action focused on text pattern(s) or characters with specific and non-specific parameters. Also, this utility package tool requires a previous base import declaration in order to operate.
Imports
In order for the regular expression utility package tool to function, there are two potential import declarations to establish. One is to declare the whole utility package tool classes alongside all its sub-classes for a general code workspace. And the other, is to declare specific utility tool sub-class(es) that focuses on a general to specific code working space. In Java, to declare an import or utility package tool to a formatted class file, the following code formats are as follows:
- Declaring the whole regex utility package tool
123import java.util.regex.*; - Declaring the specific sub classes in the regex utility package tool
1234import java.util.regex.Pattern;import java.util.regex.Matcher;
Each import declaration may possibly have a specific or general need(s), all dependent of the user’s scope and objective to accomplish.
Pattern and Matcher
These sub-classes can be set to create a matcher, resulting in a potential match against character sequences given by a string data type input by using the matcher() method using CharSequence as data type input.
In common cases, a typical match is a multiple match, which repeats the same character sequentially (e.g., "aaaeeeiiiooouu"). Also, the pattern class can create a given pattern given a string data type as input by using the compile()
method with data parameter input regex as string data type, and flag as an integer data type (flag is to be an indicator for Case Sensitiveness, Multiline, Literal events).
The matcher()
method does not have any method overloading since its only purpose is to match up a given input as character sequence versus a compiled pattern. As base case, the compiled (Pattern.compile( input )
) has to not be null to properly execute the design algorithm to match input and character sequence, else it will automatically attempt to call a new compile() regular expression if possible.
The compile()
method does have method overloading events in order to comply with two different scenarios when called. The first one, taking as parameter a string input data type regex, compiles a new Pattern(regex);
additionally, the second takes as parameters the regex string data type alongside another data type (as flag) defined as integer which functions as bit mask that includes a case insensitive (do not care for uppercase nor lowercase)
, multiline events
, literal events
.
Match any character in a range
You can use []
with chracters to get single character in the range.
For exampe:
[b-g]
: This regular expression can be used to match any single character between b and g.
Here is table for your reference:
Pattern | Description |
---|---|
"[a-z]" | Matches any character between lowercase a to z |
"[A-Z]" | Matches any character between uppercase A to Z |
"[0-9]" | Matches any character between 0 and 9 |
"[a-zA-Z]" | Matches any character between case insensitive a to z |
[bcd] | Matches any character among b,c and d |
Let’s understand with the help of example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
package org.arpit.java2blog.entry; import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexMatch { public static void main(String[] args) { // "NOT MATCH" because @ is not in range of a to z System.out.println((MatchCustomRegex("@", "[a-z]") ? ("MATCH") : ("NOT MATCH"))); // "MATCH" because b is in range of a to z System.out.println((MatchCustomRegex("@b", "@[a-z]") ? ("MATCH") : ("NOT MATCH"))); // "MATCH" because 2 is in range of 0 to 9, c is range of a to z // and $ is among these characters $,? and @. System.out.println((MatchCustomRegex("2c$", "[0-9][a-z][$?@]") ? ("MATCH") : ("NOT MATCH"))); } /** * Matches using a specific regex * @param MyInput * @param RegEx * @return */ public static boolean MatchCustomRegex(String MyInput, String RegEx) { // Attempt to match by using the regex (custom) // returns false if match failed Pattern pattern = Pattern.compile(RegEx); Matcher matcher = pattern.matcher(MyInput); return matcher.matches(); } } |
Output:
MATCH
MATCH
Excercise
Let’s practice few exercises based on Method reference.
Excercise:1
Write a regex such that :
It should match followings Strings:
a93
r21
w65
It should not match following Strings:
$65
abc
Excercise:2
Write a regex such that :
It should match followings Strings:
– xbbby
– xooo12y
– xgugy
It should not match following Strings:
– yaswx
– xaavyc
That’s all about Regex Match any character in java