{"id":124,"date":"2019-01-20T06:31:26","date_gmt":"2019-01-20T06:31:26","guid":{"rendered":"https:\/\/www.kindsonthegenius.com\/java\/?p=124"},"modified":"2019-03-02T04:37:49","modified_gmt":"2019-03-02T04:37:49","slug":"20-java-regular-expressions","status":"publish","type":"post","link":"https:\/\/kindsonthegenius.com\/java\/20-java-regular-expressions\/","title":{"rendered":"Java &#8211; Regular Expressions &#8211; 1"},"content":{"rendered":"<p>We are going to learn about\u00a0 Regular expressions in Java under the following topics:<\/p>\n<ol>\n<li><a href=\"#t1\">Introduction to Regular expressions<\/a><\/li>\n<li><a href=\"#t2\">Useful Classes in Regular Expressions<\/a><\/li>\n<li><a href=\"#t3\">Syntax of Regular Expressions<\/a><\/li>\n<li><a href=\"#t4\">Matcher Classes in Regular Expressions<\/a><\/li>\n<li><a href=\"#t5\">Demo of Regular Expressions<\/a><\/li>\n<li><a href=\"#t6\">Watch the Video<\/a><\/li>\n<\/ol>\n<p>&nbsp;<\/p>\n<h4><strong id=\"t1\">1. Introduction to Regular Expressions<\/strong><\/h4>\n<p>A regular expression is a special sequence of characters. Its also known as <strong>regex<\/strong>. You can use them to represent patterns in a text. Moreover, you can also used them to perform other operations. These includes: searching for particular pattern in a text or replacing occurrence of certain string.<\/p>\n<p>For example, you may want to search for phone numbers inside several pages of text. Regular expression comes to the rescue in cases like this.<\/p>\n<p>In Java, we have three classes used to work with regular expressions. This classes are available in java.util.regex package. They are Pattern, Matcher and PatternSyntaxException classes. Let&#8217;s now discuss each of them.<\/p>\n<p>&nbsp;<\/p>\n<h4><strong id=\"t2\">2. Useful Classes in Regular Expressions<\/strong><\/h4>\n<p>There are three of such classes. We would consider them in this section. They are:<\/p>\n<ul>\n<li>Pattern Class<\/li>\n<li>Matcher Class<\/li>\n<li>PatternSyntaxException Class<\/li>\n<\/ul>\n<p>&nbsp;<\/p>\n<p><strong>Pattern Class<\/strong><\/p>\n<p>So you can create a Pattern object from a pattern class. Hence,\u00a0 pattern object represents a particular regular expression. However, the Pattern class has not public constructors. As such, you cannot just create a Pattern object using new keyword.<\/p>\n<p>How then can you create a pattern object?<\/p>\n<p>You can do this by calling its static compile method(). This method accepts a regular expression as parameter and returns a Pattern object.<\/p>\n<p>&nbsp;<\/p>\n<p><strong>Matcher Class<\/strong><\/p>\n<p>Next class in the package is the Matcher class. The Matcher class helps you to match a string against a pattern. Just like the Pattern class, there are no public constructor in the Matcher class. However, you can create a Matcher object by calling the match() method of the Pattern object. Then you pass it the string\u00a0 you want to match.<\/p>\n<p>&nbsp;<\/p>\n<p><strong>PatternSyntaxException<\/strong><\/p>\n<p>A PatternSyntaxException object is an exception that occurs if there is error in the regular expression<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<h4><strong id=\"t3\">3. Syntax of Regular Expressions<\/strong><\/h4>\n<p>So we are going to separate the syntax into categories. This is because there are quite a number of different expressions to use.<\/p>\n<p><strong>(a) Matching Characters<\/strong><\/p>\n<table class=\"table table-bordered\" align=\"center\">\n<tbody>\n<tr style=\"background-color: #f7f6f3;\">\n<th>Expression<\/th>\n<th>Matches<\/th>\n<\/tr>\n<tr>\n<td class=\"ts\">.<\/td>\n<td>\u00a0Any character except newline.<\/td>\n<\/tr>\n<tr>\n<td>\\w<\/td>\n<td>Word character (a-z, A-Z, 0-9, _)<\/td>\n<\/tr>\n<tr>\n<td>\\W<\/td>\n<td>Not a word character<\/td>\n<\/tr>\n<tr>\n<td>\\s<\/td>\n<td>Whitespaced character.\u00a0 Same as to [\\t\\n\\r\\f].<\/td>\n<\/tr>\n<tr>\n<td>\\S<\/td>\n<td>Non-whitespace.<\/td>\n<\/tr>\n<tr>\n<td>\\d<\/td>\n<td>Any digit. Same as to [0-9].<\/td>\n<\/tr>\n<tr>\n<td>\\D<\/td>\n<td>Nondigits.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>&nbsp;<\/p>\n<p><strong>(b) Matching Boundaries<\/strong><\/p>\n<p>So we provide a list of regular expressions that matches any boundaries.<\/p>\n<table class=\"table table-bordered\" align=\"center\">\n<tbody>\n<tr style=\"background-color: #f7f6f3;\">\n<th>Subexpression<\/th>\n<th>Matches<\/th>\n<\/tr>\n<tr>\n<td>^<\/td>\n<td>Beginning of a string<\/td>\n<\/tr>\n<tr>\n<td>$<\/td>\n<td>End of a string<\/td>\n<\/tr>\n<tr>\n<td>\\b<\/td>\n<td>Word boundary<\/td>\n<\/tr>\n<tr>\n<td>\\B<\/td>\n<td>Non word boundaries.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>&nbsp;<\/p>\n<p><strong>(c) Groups<\/strong><\/p>\n<p>To work with groups you use braces. So the list is provided below.<\/p>\n<table class=\"table table-bordered\" align=\"center\">\n<tbody>\n<tr style=\"background-color: #f7f6f3;\">\n<th>Expression<\/th>\n<th>Matches<\/th>\n<\/tr>\n<tr>\n<td>[&#8230;]<\/td>\n<td>Any single character in brackets.<\/td>\n<\/tr>\n<tr>\n<td>[^&#8230;]<\/td>\n<td>Any single character not in brackets.<\/td>\n<\/tr>\n<tr>\n<td>a| b<\/td>\n<td>Matches either a or b.<\/td>\n<\/tr>\n<tr>\n<td class=\"ts\">(re)<\/td>\n<td>Groups regular expressions enclosed in brackets.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>&nbsp;<\/p>\n<p><strong>(d) Quantifiers<\/strong><\/p>\n<p>Now we consider quantifiers. You use them to match more than one character at a time. Find the list below.<\/p>\n<table class=\"table table-bordered\" align=\"center\">\n<tbody>\n<tr style=\"background-color: #f7f6f3;\">\n<th>Expression<\/th>\n<th>Matches<\/th>\n<\/tr>\n<tr>\n<td class=\"ts\">*<\/td>\n<td>0 or more occurrences of the preceding expression.<\/td>\n<\/tr>\n<tr>\n<td>+<\/td>\n<td>1 or more of the previous thing.<\/td>\n<\/tr>\n<tr>\n<td>?<\/td>\n<td>0 or 1 occurrence of the preceding expression.<\/td>\n<\/tr>\n<tr>\n<td class=\"ts\">{ n}<\/td>\n<td>Exactly n number of occurrences of the preceding expression.<\/td>\n<\/tr>\n<tr>\n<td class=\"ts\">{ n,}<\/td>\n<td>n or more occurrences of the preceding expression.<\/td>\n<\/tr>\n<tr>\n<td class=\"ts\">{ n, m}<\/td>\n<td>Range of numbers. Minimum of n and maximum of m<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>&nbsp;<\/p>\n<p>Furthermore note that metacharacters must be escaped. Metacharacters include the following:<\/p>\n<p>. [ { ( ) \\ ^ $ | ? * +<\/p>\n<p>You escape a metacharacter by preceding it with a backslash (\\)<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<h4><strong id=\"t4\">4. Matcher Class Methods<\/strong><\/h4>\n<p>You can use the methods provided by the Matcher class to perform certain operations. So there are three categories of method we would discuss. They are:<\/p>\n<ul>\n<li>Index Methods<\/li>\n<li>Verifier Methods<\/li>\n<li>Replacement Methods<\/li>\n<\/ul>\n<p>&nbsp;<\/p>\n<p><strong>The index methods<\/strong><\/p>\n<p>You use the index methods to get where a match was found. It provides the index position of the match. Returns an integer<\/p>\n<table class=\"table table-bordered\" align=\"center\">\n<tbody>\n<tr style=\"background-color: #f7f6f3;\">\n<th>SN<\/th>\n<th>Method name description<\/th>\n<\/tr>\n<tr>\n<td class=\"ts\">1<\/td>\n<td><b>start()<\/b><\/p>\n<p>This method returns the start index of the previous match.<\/td>\n<\/tr>\n<tr>\n<td class=\"ts\">2<\/td>\n<td><b>start(int group)<\/b><\/p>\n<p>Gives the start index of the subsequence captured by the given group during the previous operation.<\/td>\n<\/tr>\n<tr>\n<td class=\"ts\">3<\/td>\n<td><b>end()<\/b><\/p>\n<p>Gives the offset after the last character matched.<\/td>\n<\/tr>\n<tr>\n<td class=\"ts\">4<\/td>\n<td><b>end(int group)<\/b><\/p>\n<p>Gives the offset after the last character of the subsequence captured by the given group during the previous operation.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>&nbsp;<\/p>\n<p><strong>Verifier Methods<\/strong><\/p>\n<p>So the verifier methods are used to check an input string to verify if a patter is found. Hence, it returns true if the pattern is found. Otherwise, it returns false. Find the list below.<\/p>\n<table class=\"table table-bordered\" align=\"center\">\n<tbody>\n<tr style=\"background-color: #f7f6f3;\">\n<th>SN<\/th>\n<th>Method name and description<\/th>\n<\/tr>\n<tr>\n<td class=\"ts\">1<\/td>\n<td><b>lookingAt()<\/b><\/p>\n<p>Tries to match the input sequence, starting at the beginning of the region, against the pattern.<\/td>\n<\/tr>\n<tr>\n<td class=\"ts\">2<\/td>\n<td><b>find()<\/b><\/p>\n<p>Tries to find the next subsequence of the input sequence that matches the pattern.\u00a0Returns true if it finds a match. Otherwise return false.<\/td>\n<\/tr>\n<tr>\n<td class=\"ts\">3<\/td>\n<td><b>find(int start)<\/b><\/p>\n<p>Resets this matcher and then tries to find the next subsequence of the input sequence that matches the pattern, starting at the given index. Returns true if there is a match. Otherwise return false.<\/td>\n<\/tr>\n<tr>\n<td class=\"ts\">4<\/td>\n<td><b>matches()<\/b><\/p>\n<p>Tries to match the entire region against the pattern. Returns true if\u00a0 it finds a match. Else it returns false.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>&nbsp;<\/p>\n<p><strong>Replacement Methods<\/strong><\/p>\n<p>This methods are used to replace matching text in the input string. Find the list below<\/p>\n<table class=\"table table-bordered\" align=\"center\">\n<tbody>\n<tr style=\"background-color: #f7f6f3;\">\n<th>SN<\/th>\n<th>Method &amp; brief description<\/th>\n<\/tr>\n<tr>\n<td class=\"ts\">1<\/td>\n<td><b>Matcher appendReplacement(StringBuffer sb, String replacement)<\/b><\/p>\n<p>Implements a non-terminal append-and-replace step. Returns a Matcher<\/td>\n<\/tr>\n<tr>\n<td class=\"ts\">2<\/td>\n<td><b>StringBuffer appendTail(StringBuffer sb)<\/b><\/p>\n<p>Implements a terminal append-and-replace step. Returns a StringBuffer<\/td>\n<\/tr>\n<tr>\n<td class=\"ts\">3<\/td>\n<td><b>String replaceAll(String replacement)<\/b><\/p>\n<p>Replaces every subsequence of the input sequence that matches the pattern with the given replacement string. Then returns the new string<\/td>\n<\/tr>\n<tr>\n<td class=\"ts\">4<\/td>\n<td><b>String replaceFirst(String replacement)<\/b><\/p>\n<p>Replaces the first subsequence of the input sequence that matches the pattern with the given replacement string. The returns the new string<\/td>\n<\/tr>\n<tr>\n<td class=\"ts\">5<\/td>\n<td><b>static String quoteReplacement(String s)<\/b><\/p>\n<p>Returns a replacement String for the specified String. This method produces a String that will work as a literal replacement\u00a0<b>s<\/b>in the appendReplacement method of the Matcher class.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<h4><strong id=\"t5\">5. Demo of Regular Expressions<\/strong><\/h4>\n<p>Let&#8217;s now apply what we&#8217;ve learnt so far.<\/p>\n<p>We would\u00a0 write a regular expression that finds all 3 digit numbers in an input string<\/p>\n<p>&nbsp;<\/p>\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #008800; font-weight: bold;\">import<\/span> <span style=\"color: #0e84b5; font-weight: bold;\">java.util.regex.Matcher<\/span><span style=\"color: #333333;\">;<\/span>\r\n<span style=\"color: #008800; font-weight: bold;\">import<\/span> <span style=\"color: #0e84b5; font-weight: bold;\">java.util.regex.Pattern<\/span><span style=\"color: #333333;\">;<\/span>\r\n\r\n<span style=\"color: #008800; font-weight: bold;\">public<\/span> <span style=\"color: #008800; font-weight: bold;\">class<\/span> <span style=\"color: #bb0066; font-weight: bold;\">RegexDeom<\/span> <span style=\"color: #333333;\">{<\/span>\r\n\r\n\t<span style=\"color: #008800; font-weight: bold;\">public<\/span> <span style=\"color: #008800; font-weight: bold;\">static<\/span> <span style=\"color: #333399; font-weight: bold;\">void<\/span> <span style=\"color: #0066bb; font-weight: bold;\">main<\/span><span style=\"color: #333333;\">(<\/span>String<span style=\"color: #333333;\">[]<\/span> args<span style=\"color: #333333;\">)<\/span> <span style=\"color: #333333;\">{<\/span>\r\n\t\tPattern pt <span style=\"color: #333333;\">=<\/span> Pattern<span style=\"color: #333333;\">.<\/span><span style=\"color: #0000cc;\">compile<\/span><span style=\"color: #333333;\">(<\/span><span style=\"background-color: #fff0f0;\">\"\\\\d{3}\"<\/span><span style=\"color: #333333;\">);<\/span>\r\n\t\t\r\n\t\tString text <span style=\"color: #333333;\">=<\/span> <span style=\"background-color: #fff0f0;\">\"23 becomes 230 if you add 0 \"<\/span> <span style=\"color: #333333;\">+<\/span>\r\n\t\t<span style=\"background-color: #fff0f0;\">\"but its not same as 544 be it becomed 3\"<\/span><span style=\"color: #333333;\">;<\/span>\r\n\t\t\r\n\t\tMatcher mt <span style=\"color: #333333;\">=<\/span> pt<span style=\"color: #333333;\">.<\/span><span style=\"color: #0000cc;\">matcher<\/span><span style=\"color: #333333;\">(<\/span>text<span style=\"color: #333333;\">);<\/span>\r\n\t\t\r\n\t\t<span style=\"color: #333399; font-weight: bold;\">int<\/span> count <span style=\"color: #333333;\">=<\/span> <span style=\"color: #0000dd; font-weight: bold;\">0<\/span><span style=\"color: #333333;\">;<\/span>\t\t\r\n\t\t<span style=\"color: #008800; font-weight: bold;\">while<\/span><span style=\"color: #333333;\">(<\/span>mt<span style=\"color: #333333;\">.<\/span><span style=\"color: #0000cc;\">find<\/span><span style=\"color: #333333;\">())<\/span> <span style=\"color: #333333;\">{<\/span>\r\n\t\t\tcount <span style=\"color: #333333;\">=<\/span> count<span style=\"color: #333333;\">+<\/span> <span style=\"color: #0000dd; font-weight: bold;\">1<\/span><span style=\"color: #333333;\">;<\/span>\r\n\t\t<span style=\"color: #333333;\">}<\/span>\t\t\r\n\t\tSystem<span style=\"color: #333333;\">.<\/span><span style=\"color: #0000cc;\">out<\/span><span style=\"color: #333333;\">.<\/span><span style=\"color: #0000cc;\">println<\/span><span style=\"color: #333333;\">(<\/span>count<span style=\"color: #333333;\">);<\/span>\t\t\r\n\t<span style=\"color: #333333;\">}<\/span>\r\n<span style=\"color: #333333;\">}<\/span>\r\n<\/pre>\n<h4><a href=\"https:\/\/www.youtube.com\/watch?v=sCuOJ8uadOg\" target=\"_blank\" rel=\"noopener\"><strong id=\"t6\">6. Watch the Video<\/strong><\/a><\/h4>\n<p><iframe loading=\"lazy\" src=\"https:\/\/www.youtube.com\/embed\/sCuOJ8uadOg\" width=\"100%\" height=\"500px\" frameborder=\"0\" allowfullscreen=\"allowfullscreen\"><span data-mce-type=\"bookmark\" style=\"display: inline-block; width: 0px; overflow: hidden; line-height: 0;\" class=\"mce_SELRES_start\">\ufeff<\/span><span data-mce-type=\"bookmark\" style=\"display: inline-block; width: 0px; overflow: hidden; line-height: 0;\" class=\"mce_SELRES_start\">\ufeff<\/span><\/iframe><\/p>\n","protected":false},"excerpt":{"rendered":"<p>We are going to learn about\u00a0 Regular expressions in Java under the following topics: Introduction to Regular expressions Useful Classes in Regular Expressions Syntax of &hellip; <\/p>\n","protected":false},"author":395,"featured_media":127,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[2],"tags":[],"class_list":["post-124","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java-tutorial"],"_links":{"self":[{"href":"https:\/\/kindsonthegenius.com\/java\/wp-json\/wp\/v2\/posts\/124","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/kindsonthegenius.com\/java\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/kindsonthegenius.com\/java\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/kindsonthegenius.com\/java\/wp-json\/wp\/v2\/users\/395"}],"replies":[{"embeddable":true,"href":"https:\/\/kindsonthegenius.com\/java\/wp-json\/wp\/v2\/comments?post=124"}],"version-history":[{"count":9,"href":"https:\/\/kindsonthegenius.com\/java\/wp-json\/wp\/v2\/posts\/124\/revisions"}],"predecessor-version":[{"id":144,"href":"https:\/\/kindsonthegenius.com\/java\/wp-json\/wp\/v2\/posts\/124\/revisions\/144"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/kindsonthegenius.com\/java\/wp-json\/wp\/v2\/media\/127"}],"wp:attachment":[{"href":"https:\/\/kindsonthegenius.com\/java\/wp-json\/wp\/v2\/media?parent=124"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/kindsonthegenius.com\/java\/wp-json\/wp\/v2\/categories?post=124"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/kindsonthegenius.com\/java\/wp-json\/wp\/v2\/tags?post=124"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}