

{"id":7094,"date":"2018-02-02T12:02:39","date_gmt":"2018-02-02T12:02:39","guid":{"rendered":"https:\/\/data-flair.training\/blogs\/?p=7094"},"modified":"2026-05-28T14:52:53","modified_gmt":"2026-05-28T09:22:53","slug":"java-regular-expression","status":"publish","type":"post","link":"https:\/\/data-flair.training\/blogs\/java-regular-expression\/","title":{"rendered":"Java Regular Expression (Java Regex) with Examples"},"content":{"rendered":"<p>Java Regular expressions &#8211; It may sound confusing and difficult at first, but we will boil it down for you. In order to understand the concept of regular expressions, you need to understand the need for it. Consider a real-life example, where you need to remember a code for a gift.<\/p>\n<p>You agree to do so because you believe that you have a good memory. However, you are shocked when you see the code being around 200 characters long! You immediately realize that you are in trouble because it is impossible for you to remember that. (Because not all of us are blessed with Sheldon\u2019s memory!). So you return from where you started, disappointed, because you know you will not be able to remember it.<\/p>\n<p>Luckily, one guy asks you to say what it looked like, what its first and last characters were, and so on. This becomes easy as you do remember it! So you tell him and he figures out the rest of the code with the help of his Java program! What you said was a regular expression of the code. What it begins with, what it ended with, what characters did it have, etc. Let us learn more about Regular expressions in Java with Examples.<\/p>\n<p><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/02\/Java-Regular-Expressions-df.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-84327\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/02\/Java-Regular-Expressions-df.jpg\" alt=\"Java Regular Expressions (df)\" width=\"1200\" height=\"628\" srcset=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/02\/Java-Regular-Expressions-df.jpg 1200w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/02\/Java-Regular-Expressions-df-300x157.jpg 300w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/02\/Java-Regular-Expressions-df-1024x536.jpg 1024w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/02\/Java-Regular-Expressions-df-150x79.jpg 150w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/02\/Java-Regular-Expressions-df-768x402.jpg 768w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/02\/Java-Regular-Expressions-df-720x377.jpg 720w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/02\/Java-Regular-Expressions-df-520x272.jpg 520w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/02\/Java-Regular-Expressions-df-320x167.jpg 320w\" sizes=\"auto, (max-width: 1200px) 100vw, 1200px\" \/><\/a><\/p>\n<h3>Regular Expressions in Java<\/h3>\n<p>Regular expressions in Java comprise a series of characters that define a particular search pattern! These are extensively used in Find and Replace algorithms and search engines, where it filters out the strings based on a particular pattern.<\/p>\n<p>Famous American Mathematician Stephen Cole Kleene brought out the concept of regular expressions in the 1950s. The <strong>java.util.regex<\/strong> class in Java is extensively used for regular expressions.<\/p>\n<p><strong>It has the following interfaces and classes:<\/strong><\/p>\n<p>1. MatchResult interface<\/p>\n<p>2. Matcher class<\/p>\n<p>3. Pattern class<\/p>\n<p>4. PatternSyntaxException class<\/p>\n<p><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/02\/Interfaces-Classes-of-java-regular-expressions.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-84328\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/02\/Interfaces-Classes-of-java-regular-expressions.jpg\" alt=\"Java interface and classes\" width=\"414\" height=\"592\" srcset=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/02\/Interfaces-Classes-of-java-regular-expressions.jpg 414w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/02\/Interfaces-Classes-of-java-regular-expressions-210x300.jpg 210w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/02\/Interfaces-Classes-of-java-regular-expressions-105x150.jpg 105w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/02\/Interfaces-Classes-of-java-regular-expressions-320x458.jpg 320w\" sizes=\"auto, (max-width: 414px) 100vw, 414px\" \/><\/a><\/p>\n<h3>1. MatchResult Interface in Java<\/h3>\n<p>This interface determines the result of a match operation for a regular expression. You can see the group and the match boundaries, but you cannot modify the result through the MatchResult interface.<\/p>\n<p>The MatchResult interface in Java comes under the Java Regular expression. This interface does not perform the updation operation on the character. This method returns the output by checking the pattern in the string<\/p>\n<p><strong>This interface has the following methods:<\/strong><\/p>\n<h4>a. end() in Java<\/h4>\n<p>This method returns the index of the last character matched to the regular expression.<br \/>\nHowever, a modified version of this method enables us to specify a group whose last character matched. It then returns the index of the last match.<\/p>\n<p>This is particularly useful for returning the group\u2019s last matched character index. It has a syntax:<\/p>\n<p><strong>int end() or int end(int group);<\/strong><\/p>\n<h4>b. start() in Java<\/h4>\n<p>Contrary to the end() method, the start() method returns the starting offset of the match to the pattern specified. This method has a modified version that allows us to specify groups that match the subsequence given. The syntax of the start() method is as follows<\/p>\n<p><strong>int start() or int start(int group)<\/strong><\/p>\n<h4>c. group() in Java<\/h4>\n<p>This method returns the Character subsequence returned by the last match. There is a modified version of the method that allows us to specify the group that matched with the subsequence during the previous match operation. The syntax of the group method is:<\/p>\n<p><strong>String group() or String group(int group);<\/strong><\/p>\n<h4>d. groupCount() in Java<\/h4>\n<p>It returns the number of groups that match the given pattern. These counts are actually the number of times the pattern was similar to the character subsequence. The syntax is:<\/p>\n<p><strong>int groupCount() in Java<\/strong><\/p>\n<h3>2. Matcher class in Java<\/h3>\n<p>This class implements the MatchResult interface. As the name suggests, this class has methods that help in performing match operations on character sequences. It has various methods, namely:<\/p>\n<h4>a. boolean matches() in Java<\/h4>\n<p>This method checks whether the particular pattern matches the regular expression passed through it. It matches the text with the regex. It also creates a Matcher Instance. The syntax of this method is:<\/p>\n<p><strong>boolean matches(String regex)<\/strong><\/p>\n<h4>b. find() in Java<\/h4>\n<p>This method finds the next expression that matches the pattern. It is useful when we are searching for multiple occurrences. It goes through the entire string and returns true if the regex is present in the character sequence and false otherwise. The syntax of this method is:<\/p>\n<p><strong>boolean find()<\/strong><\/p>\n<h4>c. group() in Java<\/h4>\n<p>This method returns the input sequences that match the previous match result. Simply put, this method returns the String value which subsequence of the previous result. It has the syntax:<\/p>\n<p><strong>String group();<\/strong><\/p>\n<h4>d. start() in Java<\/h4>\n<p>This returns the starting index of the subsequence that has matched. This has the syntax:<\/p>\n<p><strong>int start();<\/strong><\/p>\n<h4>e. end() in Java<\/h4>\n<p>This returns the ending index of the subsequence that has a match. It has the syntax:<\/p>\n<p><strong>int end();<\/strong><\/p>\n<p><strong>Both of these methods, start() and end() methods, combined with the find() method, return the starting and ending indexes of the match found by the find() method.<\/strong><\/p>\n<h4>f. groupCount() in Java<\/h4>\n<p>This method is particularly useful for returning the total number of subsequences that have matched. It has the syntax:<\/p>\n<p><strong>int groupCount();<\/strong><\/p>\n<p><strong>Java program to illustrate the use of the Matcher class:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">import java.util.regex. * ;\r\npublic class PatternJavaMatcherClass {\r\n  public static void main(String args[]) {\r\n    \/\/ Let's define a pattern to search from.  \r\n    Pattern pattern = Pattern.compile(\"Da*\");\r\n\r\n    \/\/ Search above pattern in \"Data-Flair.training\" \r\n    Matcher m = pattern.matcher(\"Data-Flair.training\");\r\n\r\n    \/\/ Printing the starting and ending indexes of the pattern \r\n    \/\/ in text \r\n    System.out.println(\"Searching for pattern \" + pattern + \" in Data-Flair.training\");\r\n    while (m.find())\r\n    System.out.println(\"Pattern found from \" + m.start() + \" to \" + (m.end() - 1));\r\n  }\r\n\r\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">Searching for pattern Da* in Data-Flair.training<br \/>\nPattern found from 0 to 1<\/div>\n<h3>3. Pattern Class in Java<\/h3>\n<p>Previously, we learned about the matcher class, which is used for checking for matches of the sequence provided in the given character sequence. The pattern class defines patterns for the regex engine to work on. It is a compilation of regular expressions that define various types of patterns. There are no public constructors in this class. A compile method converts the regular expression to a pattern as elaborated below.<\/p>\n<p><strong>It has the following methods:<\/strong><\/p>\n<h4>a. compile in Java<\/h4>\n<p>This returns the instance of the Pattern after compiling the regular expression. However, a modified version of this method allows us to include flags that, when paired up with the regular expression, convert it to a pattern. It has a syntax:<\/p>\n<p><strong>static Pattern.compile(String regex) or static Pattern(String regex, int flags)<\/strong><\/p>\n<h4>b. matcher in Java<\/h4>\n<p>This method has the job of matching the sequence with the pattern compiled. This only checks the pattern, not the values.<br \/>\nIt has the syntax:<\/p>\n<p><strong>Matcher matcher(CharSequence input)<\/strong><\/p>\n<h4>c. matches in Java<\/h4>\n<p>This method does both of the jobs of compiling the regex and matching it to the character sequence together. It compiles the regex and matches it to the compiled pattern. It has the syntax:<\/p>\n<p><strong>static boolean matches(String regex, CharSequence input);<\/strong><\/p>\n<h4>d. split() in Java<\/h4>\n<p>The split method splits the input sequence, i.e, the character sequence, around the matches of its pattern. This method has a modified version with one extra argument, which is the limit specified. The syntax of this method is:<\/p>\n<p><strong>String[] split(CharSequence)<\/strong><br \/>\nor<br \/>\n<strong>String[] split(CharSequence,int limit)<\/strong><\/p>\n<h4>e. pattern() in Java<\/h4>\n<p>The pattern method returns the regular expression from the pattern compiled by the compile method.\u00a0 The pattern() method in Java gives the string form.\u00a0The syntax of the method is as follows:<\/p>\n<p><strong>String pattern()<\/strong><\/p>\n<h4>e. quote() in Java<\/h4>\n<p>This returns a String pattern literal for the specified string, which is one of the parameters passed to the method. It produces a string equivalent for later use as a pattern. The syntax of this method is:<\/p>\n<p><strong>static String quote(String variable);<\/strong><\/p>\n<h4>f. toString() in Java<\/h4>\n<p>This method has the function of returning the string rendition of the pattern. This makes it easy to perform string manipulations on the pattern because it gets converted to a String object. It has the syntax:<\/p>\n<p><strong>String toString();<\/strong><\/p>\n<p><strong>Java program to illustrate the Java Pattern class:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">package com.dataflair.regexjava;\r\nimport java.util.regex. * ;\r\npublic class PatternJava {\r\n  public static void main(String[] args) {\r\n    \/\/We define the regular expression first.\r\n    \/\/For that we shall use Pattern object and compile pattern. \r\n    System.out.println(\"The first method of using regex\");\r\n    Pattern p = Pattern.compile(\".ataFlair\"); \/\/ the dot(.) represents a single character\r\n    Matcher m = p.matcher(\"DataFlair\");\r\n    boolean isMatch = m.matches();\r\n    System.out.println(isMatch);\r\n    \/\/This is the first way of creating a regex program\r\n\r\n    \/\/the second way of using Regex in Java is\r\n    System.out.println(\"The second method of using regex\");\r\n    boolean isMatch2 = Pattern.compile(\".ataFlair\").matcher(\"DataFlair\").matches();\r\n    System.out.println(isMatch2);\r\n\r\n    \/\/the third and the simplest way of creating regex\r\n    System.out.println(\"The third method of using regex\");\r\n    boolean isMatch3 = Pattern.matches(\".ataFlair\", \"DataFlair\");\r\n    System.out.println(isMatch3);\r\n\r\n    \/\/These are the basic ways of regex in Java    \r\n\r\n  }\r\n\r\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">The first method of using regex<br \/>\ntrue<br \/>\nThe second method of using regex<br \/>\ntrue<br \/>\nThe third method of using regex<br \/>\ntrue<\/div>\n<p>The output of the matches method depends on the pattern matching the character stream passed through it. The dot represents a single character. That is why.ataFlair matches with DataFlair because the single character (.) matches with the character D. Any character in place of D would have resulted in true.<\/p>\n<p>However, any change in the length of the sequence or the presence of any other characters other than the specified characters would result in a false output.<\/p>\n<h3>4. Pattern Syntax Exception Class in Java<\/h3>\n<p>Errors may occur when evaluating a regular expression. This object of the regex class has the job of identifying unchecked exceptions. Some of the methods are:<\/p>\n<h4>a. getDescription() in Java<\/h4>\n<p>The sole function of this method is to return the description of the error encountered while executing the program. It has the syntax:<\/p>\n<p><strong>String getDescription()<\/strong><\/p>\n<h4>b. getIndex() in Java<\/h4>\n<p>This method returns the index at which the error has occurred. Particularly useful when there is a need to manipulate the strings in that particular position. The syntax is:<\/p>\n<p><strong>int getIndex()<\/strong><\/p>\n<h4>c. getMessage() in Java<\/h4>\n<p>This method returns the entire error message containing the description of the error, the pattern of the regular expression(if it has errors), and a visual indication of the error index within the pattern. The syntax of the following is:<\/p>\n<p><strong>String getMessage()<\/strong><\/p>\n<h4>d. getPattern() in Java<\/h4>\n<p>This method returns the erroneous pattern of the regex while passing through the character sequence. This method has a syntax like:<\/p>\n<p><strong>String getPattern()<\/strong><\/p>\n<p><strong>Java program to illustrate the use of PatternSyntax Exception Class in Java:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">package com.dataflar.regexjava;\r\nimport java.util.regex.Matcher;\r\nimport java.util.regex.Pattern;\r\nimport java.util.regex.PatternSyntaxException;\r\n\r\npublic class BasicMethod {\r\n  private static String REGEX = \"[\";\r\n  private static String INPUT = \"DataFlair is a great palce to learn \" + \"DataFlair has a wide range of articles!.\";\r\n  private static String REPLACE = \"Java\";\r\n\r\n  public static void main(String[] args) {\r\n    try {\r\n      Pattern pattern = Pattern.compile(REGEX);\r\n\r\n      \/\/ get a matcher object\r\n      Matcher matcher = pattern.matcher(INPUT);\r\n      INPUT = matcher.replaceAll(REPLACE);\r\n    } catch(PatternSyntaxException e) {\r\n      System.out.println(\"PatternSyntaxException: \");\r\n      System.out.println(\"Description: \" + e.getDescription());\r\n      System.out.println(\"Index: \" + e.getIndex());\r\n      System.out.println(\"Message: \" + e.getMessage());\r\n      System.out.println(\"Pattern: \" + e.getPattern());\r\n    }\r\n  }\r\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">PatternSyntaxException:<br \/>\nDescription: Unclosed character class<br \/>\nIndex: 0<br \/>\nMessage: Unclosed character class near index 0<br \/>\n[<br \/>\n^<br \/>\nPattern: [<\/div>\n<h3>Character Class in Java<\/h3>\n<p>Before we progress further into the article, it is essential that we know about the concept of character class in Java. With the help of character classes, we can search for specific characters. These classes ask the compiler to search for a specific set of characters as mentioned by a programmer.<\/p>\n<p>For example, if you have to search for a character that can be any one of h,k, or i, you can simply enclose these three characters within box brackets. This will tell the compiler to search for h,k, or i in the character argument. If the characters are present, then the method will return true. If not, it returns false. One can add additional rules based on the requirements of the program.<\/p>\n<p><strong>There are certain characters that you need to be familiar with:<\/strong><\/p>\n<p><strong>1. (^):<\/strong>\u00a0This token negates the values, i.e., the complement of the values.<\/p>\n<p><strong>2. (-):<\/strong> This token denotes a range of characters.<\/p>\n<p><strong>3. (&amp;&amp;):<\/strong>\u00a0used to attach additional character classes to a class.<\/p>\n<p>Let us look at some examples of the regex character classes in Java.<\/p>\n<p><strong>a. [abc]:<\/strong> This represents a simple class of a sequence carrying a,b, or c<\/p>\n<p><strong>b. [^abc]:<\/strong> This represents any character except a, b, or c.<\/p>\n<p><strong>c. [a-zA-Z]:<\/strong> This represents any character from a-z or A-Z.<\/p>\n<p><strong>d. [a-c[w-z]]:<\/strong> This represents characters from a-c union w-z.<\/p>\n<p><strong>e. [a-x&amp;&amp;[def]]:<\/strong> This represents characters d,e, or f. This is an example of intersection<\/p>\n<p><strong>f. [a-z&amp;&amp;[^de]]:<\/strong> This represents all characters from a to z except d and e.<\/p>\n<p><strong>g. [a-z&amp;&amp;[^m-p]]:<\/strong>\u00a0This represents the characters from a-z and none of the characters from m to p.<\/p>\n<p><strong>Java program to illustrate the use of the Character class in Java:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">package com.dataflair.regexjava;\r\nimport java.util.regex. * ;\r\npublic class CharacterClassRegex {\r\n  public static void main(String[] args) {\r\n    boolean isMatch = Pattern.matches(\"[a-z]\", \"a\"); \/\/true because a lies in the mentioned limit\r\n    System.out.println(isMatch);\r\n    isMatch = Pattern.matches(\"[a-zA-Z0-9]\", \"D\"); \/\/true because D lies in the mentioned conditions\r\n    System.out.println(isMatch);\r\n    isMatch = Pattern.matches(\"[a-zA-Z&amp;&amp;[^pqn]]\", \"p\"); \/\/false because the expression excludes p. . \r\n    System.out.println(isMatch);\r\n\r\n  }\r\n\r\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">true<br \/>\ntrue<br \/>\nfalse<\/div>\n<h3>Java Regex Quantifiers<\/h3>\n<p>If you have to specify the number of character occurrences, too, then you can use quantifiers to add additional conditions on the characters.<br \/>\nSome of the quantifiers are:<\/p>\n<ul>\n<li><strong>A?:<\/strong>\u00a0Checks if A occurs once or not at all.<\/li>\n<li><strong>A+:<\/strong>\u00a0Checks if A occurs one or more times.<\/li>\n<li><strong>A*:<\/strong>\u00a0Checks if A occurs zero or more times.<\/li>\n<li><strong>A{n}: <\/strong>Checks if A occurs exactly n times.<\/li>\n<li><strong>A{n,<\/strong> &#8211; Checks if A occurs n times or more.<\/li>\n<li><strong>A{m,n}<\/strong> &#8211; Checks if A occurs at least m times but less than n times.<\/li>\n<\/ul>\n<p><strong>Java program to illustrate the usage of Quantifiers:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">package com.dataflair.regexjava;\r\nimport java.util.regex. * ;\r\npublic class PatternJavaQuantRegex {\r\n  public static void main(String[] args) {\r\n    boolean isMatch = Pattern.matches(\"[jav]?\", \"java\"); \/\/false  because j,a,v must be present only once.        \r\n    System.out.println(isMatch);\r\n    isMatch = Pattern.matches(\"[jav]+\", \"java\"); \/\/true because each and every character has occurred once or more than once\r\n    System.out.println(isMatch);\r\n    isMatch = Pattern.matches(\"[jav]*\", \"javaaa\"); \/\/true because the letters j,v,a has occurred zero or more times. \r\n    System.out.println(isMatch);\r\n\r\n  }\r\n\r\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">false<br \/>\ntrue<br \/>\ntrue<\/div>\n<h3>Java Replacement Methods<\/h3>\n<p>These methods have the function of replacing text inside an input string. In regex programming, they are very important. Some of these methods are:<\/p>\n<h4>1. appendReplacement() in java<\/h4>\n<p>This replaces the compiled character or word with the given input and then appends or adds the replacement at the end of the string buffer. This has the syntax:<\/p>\n<p><strong>public Matcher appendReplacement(String Buffer ob, String replacement)<\/strong><\/p>\n<h4>2. replaceAll() in java<\/h4>\n<p>This method replaces all the character subsequences that match the given sequence with the given string as a replacement. Its syntax is:<\/p>\n<p><strong>public String replaceAll(String replacement)<\/strong><\/p>\n<h4>3. replaceFirst() in java<\/h4>\n<p>This method, unlike the replaceAll method, replaces the first subsequence of the character sequence provided as the input, which matches with the compiled pattern, with the given replacement string. This has a syntax:<\/p>\n<p><strong>public String replaceFirst(String replacestring)<\/strong><\/p>\n<h4>4. quoteReplacement() in java<\/h4>\n<p>The method quoteReplacement, as the name suggests, returns a replacement string that can be a literal replacement for the appendReplacement method. The syntax of this method is:<\/p>\n<p><strong>public static String quoteReplacement(String str);<\/strong><\/p>\n<p><strong>Java program to illustrate the use of replacement methods in Java:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">package com.dataflair.regexjava;\r\nimport java.util.regex. * ;\r\npublic class ReplaceMethods {\r\n  public static void main(String args[]) {\r\n    String orgstr = new String(\"the quick brown fox jumped over the lazy dog\");\r\n    System.out.println(\"Original String is ': \" + orgstr);\r\n    System.out.println(\"String after replacing 'fox' with 'dog': \" + orgstr.replace(\"fox\", \"dog\"));\r\n    System.out.println(\"String after replacing all 't' with 'a': \" + orgstr.replace('t', 'a'));\r\n\r\n    String sent = \"DataFlair is a great place to go for learning\";\r\n    \/\/remove white spaces from the sentence\r\n    String str2 = sent.replaceAll(\"\\\\s\", \"\");\r\n    System.out.println(str2);\r\n\r\n    sent = \"This website also provides free tutorials on Java,Python and even Machine Learning! \";\r\n    \/\/Only Replace first 's' with 'r' in the entire sentence.  \r\n    String str1 = sent.replaceFirst(\"s\", \"r\");\r\n    System.out.println(str1);\r\n  }\r\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">Original String is &#8216;: the quick brown fox jumped over the lazy dog<br \/>\nString after replacing &#8216;fox&#8217; with &#8216;dog&#8217;: the quick brown dog jumped over the lazy dog<br \/>\nString after replacing all &#8216;t&#8217; with &#8216;a&#8217;: ahe quick brown fox jumped over ahe lazy dog<br \/>\nDataFlairisagreatplacetogoforlearning<br \/>\nTheir website also provides free tutorials on Java, Python, and even Machine Learning!<\/div>\n<h3>Metacharacters in Java<\/h3>\n<p>These are the metacharacters that act as shortcodes. They represent a special feature while specifying regular expressions. Each of them is equally important, and pairing them up with character classes can create very effective regular expressions. These represent a variety of information, as we will be seeing now:<\/p>\n<p><strong>1.<\/strong> <strong>Dot(.):<\/strong> This represents any character that may or may not match a terminator.<br \/>\n<strong>2.<\/strong> <strong>\\d:<\/strong> This represents digits, i.e., [0-9]<br \/>\n<strong>3.<\/strong> <strong>\\D:<\/strong> Non-digits, which is short for [^0-9]<br \/>\n<strong>4.<\/strong> <strong>\\s:<\/strong> This metacharacter represents any whitespace character, i.e, \\t,\\n,\\r, etc<br \/>\n<strong>5.<\/strong> <strong>\\S:<\/strong> This represents any non-whitespace character, i.e, [^\\s]<br \/>\n<strong>6.<\/strong> <strong>\\w:<\/strong> This represents a word character, i.e., [a-zA-Z_0-9]<br \/>\n<strong>7.\u00a0\\W:<\/strong> This represents non-word characters, i.e., [^\/w]<br \/>\n<strong>8.<\/strong> <strong>\\b:<\/strong> This represents a word boundary.<br \/>\n<strong>9.<\/strong> <strong>\\B:<\/strong> This represents a non-word boundary<\/p>\n<p><strong>Java program to illustrate the use of Java metacharacters:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">package com.dataflair.regexjava;\r\nimport java.util.regex. * ;\r\npublic class MetaCharacterRegex {\r\n  public static void main(String[] args) {\r\n    System.out.println(Pattern.matches(\"\\\\d\", \"dataflair\")); \/\/false (non-digit)  \r\n    System.out.println(Pattern.matches(\"\\\\d\", \"1\")); \/\/true (digit and comes once)  \r\n    System.out.println(Pattern.matches(\"\\\\d\", \"78643\")); \/\/false (digit but comes more than once)  \r\n    System.out.println(Pattern.matches(\"\\\\d\", \"3723ytec\")); \/\/false (digit and char)\r\n\r\n    System.out.println(Pattern.matches(\"\\\\D\", \"abc\")); \/\/false (non-digit but comes more than once)  \r\n    System.out.println(Pattern.matches(\"\\\\D\", \"9\")); \/\/false (digit)  \r\n    System.out.println(Pattern.matches(\"\\\\D\", \"12873\")); \/\/false (digit)  \r\n    System.out.println(Pattern.matches(\"\\\\D\", \"390()3@bc\")); \/\/false (digit and char)  \r\n    System.out.println(Pattern.matches(\"\\\\D\", \"(\")); \/\/true (non-digit and comes once) \r\n\r\n  }\r\n\r\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">false<br \/>\ntrue<br \/>\nfalse<br \/>\nfalse<br \/>\nfalse<br \/>\nfalse<br \/>\nfalse<br \/>\nfalse<br \/>\ntrue<\/div>\n<p><strong>Example of Regular Expressions in Java\u00a0<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">package com.dataflair.regexjava;\r\nimport java.util.regex. * ;\r\npublic class JavaRegexExample {\r\n  public static void main(String args[]) {\r\n    System.out.println(\"We will evaluate phone numbers in this program\");\r\n    System.out.println(\"Each phone number should be of 10 digits and should start with 4,5,6\");\r\n    System.out.println(\"We will take the help of character class moderators. \");\r\n    System.out.println(\"Is 5953038949 a valid number? \" + Pattern.matches(\"[456]{1}[0-9]{9}\", \"5953038949\")); \/\/true  \r\n    System.out.println(\"Is 59537657755949 a valid number? \" + Pattern.matches(\"[456][0-9]{9}\", \"59537657755949\")); \/\/false because more than 10 characters\r\n\r\n    System.out.println(\"Is 99530112290 a valid number? \" + Pattern.matches(\"[456][0-9]{9}\", \"99530112290\")); \/\/false (11 characters and starts with 9)  \r\n    System.out.println(\"Is 6953038949 a valid number? \" + Pattern.matches(\"[456][0-9]{9}\", \"6953038949\")); \/\/true (starts with 6)  \r\n    System.out.println(\"Is 4333038949 a valid number? \" + Pattern.matches(\"[456][0-9]{9}\", \"4333038949\") + \"\\n\"); \/\/true  (starts with 4)\r\n\r\n    System.out.println(\"With the help of metacharacters!! \\n\");\r\n    System.out.println(\"Is 6353038949 a valid number? \" + Pattern.matches(\"[456]{1}\\\\d{9}\", \"6353038949\")); \/\/true  \r\n    System.out.println(\"Is 3853038949 a valid number? \" + Pattern.matches(\"[456]{1}\\\\d{9}\", \"3853038949\")); \/\/false (starts from 3)\r\n\r\n    System.out.println(\"The metacharacters help in identifying only digits i.e, [0-9]\");\r\n  }\r\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">We will evaluate phone numbers in this program<br \/>\nEach phone number should be of 10 digits and should start with 4,5,6<br \/>\nWe will take the help of character class moderators.<br \/>\nIs 5953038949 a valid number? true<br \/>\nIs 59537657755949 a valid number? false<br \/>\nIs 99530112290 a valid number? false<br \/>\nIs 6953038949 a valid number? true<br \/>\nIs 4333038949 a valid number? trueWith the help of metacharacters!!Is 6353038949 a valid number? true<br \/>\nIs 3853038949 a valid number? false<br \/>\nThe metacharacters help in identifying only digits i.e, [0-9]<\/div>\n<h3>Java Facts and Observations<\/h3>\n<p>a. compile() is a static method in the Pattern Class.<br \/>\nb. We do not create a constructor of the compile() method. Instead, we create an object of type pattern while calling the compile()method.<br \/>\nc. We also create an object of type matcher by calling the matcher() object.<br \/>\nd. This method is also static in itself and checks whether the pattern provided matches the text.<br \/>\ne. When we want to find multiple occurrences of a pattern in a text sequence, we use the find() method.<br \/>\nf. The split() method splits a text based on a delimiter pattern in the text. \u2018<\/p>\n<h3>Summary<\/h3>\n<p>In this article, we learned about the various methods and classes that, together, build the java.util.regex class. Regular Expressions are frequently used in search engines and distributed systems. Hence, a strong concept of the same is extremely important for future developers.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Java Regular expressions &#8211; It may sound confusing and difficult at first, but we will boil it down for you. In order to understand the concept of regular expressions, you need to understand the&#46;&#46;&#46;<\/p>\n","protected":false},"author":5,"featured_media":84327,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[32],"tags":[2312,7439,7472,7497,7591,7635,7666,7684,7694,7753,11479,12885],"class_list":["post-7094","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java","tag-case-insensitive-searching-in-java","tag-java-complie","tag-java-end","tag-java-find","tag-java-matcher-class","tag-java-pattern-class","tag-java-regular-expression","tag-java-split","tag-java-start","tag-java-util-regex-matcher-class","tag-regular-expression-in-java","tag-simple-pattern-searching-in-java"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.4 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Java Regular Expression (Java Regex) with Examples - DataFlair<\/title>\n<meta name=\"description\" content=\"Java Regular Expression-Java Regex,Java Pattern class,java Matcher Class,Example to Demonstrate Working of compile,find,start,end,split\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/data-flair.training\/blogs\/java-regular-expression\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Java Regular Expression (Java Regex) with Examples - DataFlair\" \/>\n<meta property=\"og:description\" content=\"Java Regular Expression-Java Regex,Java Pattern class,java Matcher Class,Example to Demonstrate Working of compile,find,start,end,split\" \/>\n<meta property=\"og:url\" content=\"https:\/\/data-flair.training\/blogs\/java-regular-expression\/\" \/>\n<meta property=\"og:site_name\" content=\"DataFlair\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/DataFlairWS\/\" \/>\n<meta property=\"article:published_time\" content=\"2018-02-02T12:02:39+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2026-05-28T09:22:53+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/02\/Java-Regular-Expressions-df.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"DataFlair Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:site\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"DataFlair Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"12 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Java Regular Expression (Java Regex) with Examples - DataFlair","description":"Java Regular Expression-Java Regex,Java Pattern class,java Matcher Class,Example to Demonstrate Working of compile,find,start,end,split","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/data-flair.training\/blogs\/java-regular-expression\/","og_locale":"en_US","og_type":"article","og_title":"Java Regular Expression (Java Regex) with Examples - DataFlair","og_description":"Java Regular Expression-Java Regex,Java Pattern class,java Matcher Class,Example to Demonstrate Working of compile,find,start,end,split","og_url":"https:\/\/data-flair.training\/blogs\/java-regular-expression\/","og_site_name":"DataFlair","article_publisher":"https:\/\/www.facebook.com\/DataFlairWS\/","article_published_time":"2018-02-02T12:02:39+00:00","article_modified_time":"2026-05-28T09:22:53+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/02\/Java-Regular-Expressions-df.jpg","type":"image\/jpeg"}],"author":"DataFlair Team","twitter_card":"summary_large_image","twitter_creator":"@DataFlairWS","twitter_site":"@DataFlairWS","twitter_misc":{"Written by":"DataFlair Team","Est. reading time":"12 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/data-flair.training\/blogs\/java-regular-expression\/#article","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/java-regular-expression\/"},"author":{"name":"DataFlair Team","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/7f83c342f5d1632d6f7b4b0b0f447823"},"headline":"Java Regular Expression (Java Regex) with Examples","datePublished":"2018-02-02T12:02:39+00:00","dateModified":"2026-05-28T09:22:53+00:00","mainEntityOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/java-regular-expression\/"},"wordCount":2600,"commentCount":0,"publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/java-regular-expression\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/02\/Java-Regular-Expressions-df.jpg","keywords":["Case Insensitive Searching in Java","java complie","java end","Java find","Java matcher class","java pattern class","Java Regular Expression","java split","java start","Java.util.regex.Matcher Class","regular expression in java","Simple pattern searching in Java"],"articleSection":["Java Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/data-flair.training\/blogs\/java-regular-expression\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/data-flair.training\/blogs\/java-regular-expression\/","url":"https:\/\/data-flair.training\/blogs\/java-regular-expression\/","name":"Java Regular Expression (Java Regex) with Examples - DataFlair","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/#website"},"primaryImageOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/java-regular-expression\/#primaryimage"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/java-regular-expression\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/02\/Java-Regular-Expressions-df.jpg","datePublished":"2018-02-02T12:02:39+00:00","dateModified":"2026-05-28T09:22:53+00:00","description":"Java Regular Expression-Java Regex,Java Pattern class,java Matcher Class,Example to Demonstrate Working of compile,find,start,end,split","breadcrumb":{"@id":"https:\/\/data-flair.training\/blogs\/java-regular-expression\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/data-flair.training\/blogs\/java-regular-expression\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/java-regular-expression\/#primaryimage","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/02\/Java-Regular-Expressions-df.jpg","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/02\/Java-Regular-Expressions-df.jpg","width":1200,"height":628,"caption":"Java Regular Expressions (df)"},{"@type":"BreadcrumbList","@id":"https:\/\/data-flair.training\/blogs\/java-regular-expression\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Blog Home","item":"https:\/\/data-flair.training\/blogs\/"},{"@type":"ListItem","position":2,"name":"Java Tutorials","item":"https:\/\/data-flair.training\/blogs\/category\/java\/"},{"@type":"ListItem","position":3,"name":"Java Regular Expression (Java Regex) with Examples"}]},{"@type":"WebSite","@id":"https:\/\/data-flair.training\/blogs\/#website","url":"https:\/\/data-flair.training\/blogs\/","name":"DataFlair","description":"Learn Today. Lead Tomorrow.","publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/data-flair.training\/blogs\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/data-flair.training\/blogs\/#organization","name":"DataFlair","url":"https:\/\/data-flair.training\/blogs\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","width":106,"height":48,"caption":"DataFlair"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/DataFlairWS\/","https:\/\/x.com\/DataFlairWS","https:\/\/www.linkedin.com\/company\/dataflair-web-services-pvt-ltd\/","https:\/\/www.youtube.com\/user\/DataFlairWS"]},{"@type":"Person","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/7f83c342f5d1632d6f7b4b0b0f447823","name":"DataFlair Team","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/4cf3a74600d131330b8c481d519afd1574093ed89f6d3396a95393ad223eb7cd?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/4cf3a74600d131330b8c481d519afd1574093ed89f6d3396a95393ad223eb7cd?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/4cf3a74600d131330b8c481d519afd1574093ed89f6d3396a95393ad223eb7cd?s=96&d=mm&r=g","caption":"DataFlair Team"},"description":"DataFlair Team creates expert-level guides on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our goal is to empower learners with easy-to-understand content. Explore our resources for career growth and practical learning.","url":"https:\/\/data-flair.training\/blogs\/author\/dfteam1\/"}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/7094","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/comments?post=7094"}],"version-history":[{"count":15,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/7094\/revisions"}],"predecessor-version":[{"id":148454,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/7094\/revisions\/148454"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media\/84327"}],"wp:attachment":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media?parent=7094"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/categories?post=7094"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/tags?post=7094"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}