{"id":329569,"date":"2024-05-23T01:51:08","date_gmt":"2024-05-23T01:51:08","guid":{"rendered":"https:\/\/www.baeldung.com\/replacing-strings-in-java-using-regex-back-reference-vs-lookaround"},"modified":"2024-05-23T01:51:08","modified_gmt":"2024-05-23T01:51:08","slug":"replacing-strings-in-java-using-regex-back-reference-vs-lookaround","status":"publish","type":"post","link":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/2024\/05\/23\/replacing-strings-in-java-using-regex-back-reference-vs-lookaround\/","title":{"rendered":"Replacing Strings in Java Using Regex: Back Reference vs. Lookaround"},"content":{"rendered":"<p class=\"syndicated-attribution\"><meta name= \\\"keywords \\\" content= \\\"\u96fb\u5b50\u8a08\u7b97\u6a5f, \u6559\u80b2, IT \u96fb\u8166\u73ed,\u96fb\u8166\u88dc\u7fd2\uff0c \u96fb\u8166\u73ed\uff0c \u5bb6\u6559\uff0c \u79c1\u4eba\u8001\u5e2b\uff0c \u8cc7\u8a0a\u6280\u8853\uff0c \u7a0b\u5e8f\u8a2d\u8a08\uff0c \u96fb\u5b50\u8a08\u7b97\u6a5f\uff0c \u904a\u6232\uff0c \u860b\u679c\uff0c \u96fb\u5f71\uff0c \u8a08\u7b97\u6a5f\uff0c\u7de8\u78bc\uff0c Java\uff0c C\/C++\uff0c JavaScript\uff0c PHP\uff0c HTML\uff0c CSS\uff0c MySQL\uff0c mobile\uff0c Android\uff0c \u52d5\u6f2b\uff0c Python\uff0c teacher\uff0c \u88dc\u7fd2\uff0c \u96fb\u8166\u88dc\u7fd2 \u8cc7\u8a0a, \u7535\u5b50\u8ba1\u7b97\u673a, IT ,Game, apple, movie, Computer,student,Java,\u6559\u80b2, ,\u5b66\u751f, \u5b66\u4e60, learn, \u6559\u5b66,  Android, apple,anime, animation, \u4fe1\u606f\u6280\u672f, \u7a0b\u5e8f\u8bbe\u8ba1, \u79fb\u52a8\u7535\u8bdd, \u8cc7\u8a0a\u79d1\u6280,Game, Jeu, Juego,Call Of Duty ,\u4f7f\u547d\u53ec\u559a , \u6e38\u620f, \u7535\u5b50\u6e38\u620f,, \u591a\u4eba\u7535\u5b50\u6e38\u620f, \u7f51\u7edc\u6e38\u620f\uff0conline\uff0conline game, \u624b\u673a\u6e38\u620f, mobile \\\"><\/p>\n<p><img src=\"https:\/\/www.baeldung.com\/wp-content\/uploads\/2016\/10\/social-Java-On-Baeldung-2.jpg\" class=\"webfeedsFeaturedVisual wp-post-image\" alt=\"\" style=\"float: left; margin-right: 5px;\" decoding=\"async\" srcset=\"https:\/\/www.baeldung.com\/wp-content\/uploads\/2016\/10\/social-Java-On-Baeldung-2.jpg 952w, https:\/\/www.baeldung.com\/wp-content\/uploads\/2016\/10\/social-Java-On-Baeldung-2-300x157.jpg 300w, https:\/\/www.baeldung.com\/wp-content\/uploads\/2016\/10\/social-Java-On-Baeldung-2-768x402.jpg 768w\" sizes=\"(max-width: 580px) 100vw, 580px\" \/><\/p>\n<h2 id=\"bd-overview\" data-id=\"overview\">1. Overview<\/h2>\n<div class=\"bd-anchor\" id=\"overview\"><\/div>\n<p>In this tutorial, we&#8217;ll examine how to use the <em>replaceAll()<\/em> provided in the <em>String<\/em> class to replace text using regular expressions. Additionally, we&#8217;ll learn two methods, back reference and <a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/www.baeldung.com\/java-regex-lookahead-lookbehind\">lookaround<\/a>, to perform the same operation and then compare their performance.<\/p>\n<p>Let&#8217;s begin by describing the first method.<\/p>\n<h2 id=\"bd-using-back-reference-with-replaceall\" data-id=\"using-back-reference-with-replaceall\">2. Using Back Reference With <em>replaceAll()<\/em><\/h2>\n<div class=\"bd-anchor\" id=\"using-back-reference-with-replaceall\"><\/div>\n<p>To understand back reference, we first need to learn about matching groups. In short, a group is nothing but multiple characters seen as a single unit. So, back-references is a feature in regular expressions that allows us to refer back to previously matched groups within the same regex. Typically, we denote them with numbers that refer to the <a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/www.baeldung.com\/regular-expressions-java#Capturing\">capturing group<\/a> in the pattern, like <em>\\1<\/em>, <em>\\2<\/em>, etc.<\/p>\n<p>For example, the regex <em>(a)(b)\\1<\/em> uses <em>\\1<\/em> to refer back to the first captured group, which in our case is <em>(a)<\/em>.<\/p>\n<p>In string replacement operations, we use these references to replace the matching text with the one we want. <strong>When using the <em>replaceAll()<\/em> method, we refer to a capturing group in the replacement string as <em>$1<\/em>, <em>$2<\/em>, etc.<\/strong><\/p>\n<p>Now, to understand better, let&#8217;s consider the following use case. We want to remove all the asterisk symbols within a string. So, the task is to preserve asterisks only if they appear at the beginning or the end of a string while removing all others. For example, <em>*text*<\/em> remains unaltered while <em>**te*x**t**<\/em> becomes <em>*text*<\/em>.<\/p>\n<h3 id=\"bd-1-implement-back-reference\" data-id=\"1-implement-back-reference\">2.1. Implement Back Reference<\/h3>\n<div class=\"bd-anchor\" id=\"1-implement-back-reference\"><\/div>\n<p>To complete our task, we&#8217;ll use the <em>replaceAll()<\/em> method with a regular expression and use the backreference in:<\/p>\n<pre><code class=\"language-java\">String str = &quot;**te*xt**&quot;;\r\nString replaced = str.replaceAll(&quot;(^\\\\*)|(\\\\*$)|\\\\*&quot;, &quot;$1$2&quot;);\r\nassertEquals(&quot;*text*&quot;, replaced);<\/code><\/pre>\n<p>Above, we are defining the regular expression <em>&#8220;(^\\\\*)|(\\\\*$)|\\\\*&#8221;<\/em> which is made of three parts. The first group <em>(^\\\\*)<\/em> captures the asterisk at the beginning of the string. The second group <em>(\\\\*$)<\/em> captures the asterisk at the end of the string. The third group <em>\\\\*<\/em> captures all the rest of the asterisks. So, the regex only selects certain parts of the string, and only those selected parts will be replaced. We highlight the different parts with different colors:<\/p>\n<p><a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/www.baeldung.com\/wp-content\/uploads\/2024\/05\/Senza-titolo-2024-05-01-1838.png\"><img decoding=\"async\" class=\"aligncenter size-medium wp-image-198754\" src=\"https:\/\/www.baeldung.com\/wp-content\/uploads\/2024\/05\/Senza-titolo-2024-05-01-1838-300x164.png\" alt=\"\" \/><\/a><\/p>\n<p>In short, the replacement string <em>$1$2<\/em> returns all the selected characters in that group so they are kept in the final string.<\/p>\n<p>Let&#8217;s look at a different approach to solving the same task.<\/p>\n<h2 id=\"bd-using-lookaround-with-replaceall\" data-id=\"using-lookaround-with-replaceall\">3. Using Lookaround With <em>replaceAll()<\/em><\/h2>\n<div class=\"bd-anchor\" id=\"using-lookaround-with-replaceall\"><\/div>\n<p>An alternative approach to back reference is using lookarounds, which allow us to ignore the surrounding characters when doing the match in the regular expression. In our example, we can remove the asterisks within the string in a more intuitive way:<\/p>\n<pre><code class=\"language-java\">String str = &quot;**te*xt**&quot;;\r\nString replacedUsingLookaround = str.replaceAll(&quot;(?&lt;!^)\\\\*+(?!$)&quot;, &quot;&quot;);\r\nassertEquals(&quot;*text*&quot;, replacedUsingLookaround);<\/code><\/pre>\n<p>In this example,<em> (?&lt;!^)\\\\*+<\/em> captures one or more asterisks (\\\\*+) that don&#8217;t have the start of the string before them <em>((?&lt;!^))<\/em>. In short, we are doing a <a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/www.baeldung.com\/java-regex-lookahead-lookbehind#negative-lookbehind\">negative look behind<\/a>. Next, the <em>(?!$)<\/em> part is a negative lookahead that we define to ignore asterisks that are followed by the end of the string. Finally, the empty replacement string here removes all the matching characters. Therefore, this method is more easy to reason about as we are selecting all the characters we want to remove:<\/p>\n<p><a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/www.baeldung.com\/wp-content\/uploads\/2024\/05\/Senza-titolo-2024-05-01-18381.png\"><img decoding=\"async\" class=\"aligncenter size-medium wp-image-198761\" src=\"https:\/\/www.baeldung.com\/wp-content\/uploads\/2024\/05\/Senza-titolo-2024-05-01-18381-300x164.png\" alt=\"\" \/><\/a><\/p>\n<p>Apart from readability, these two methods differ in performance. Let&#8217;s check them out next.<\/p>\n<h2 id=\"bd-performance-lookaround-vs-back-reference\" data-id=\"performance-lookaround-vs-back-reference\">4. Performance Lookaround vs. Back Reference<\/h2>\n<div class=\"bd-anchor\" id=\"performance-lookaround-vs-back-reference\"><\/div>\n<p>To compare the performance of both of these methods, we&#8217;ll use the <a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/www.baeldung.com\/java-microbenchmark-harness\">JMH<\/a> library to benchmark and measure the average execution time required for each method to process a large number of string replacements.<\/p>\n<p>For our performance test, we&#8217;ll use the same asterisk example from the previous task. In short, we&#8217;ll repeatedly use the\u00a0<em>replaceAll()<\/em> function with the two regex methods 1000 times.<\/p>\n<p>For this test, we&#8217;ll configure 2 warmup iterations and 5 measurement iterations. Additionally, we&#8217;ll measure the average time taken to complete the task:<\/p>\n<pre><code class=\"language-java\">@BenchmarkMode(Mode.AverageTime)\r\n@OutputTimeUnit(TimeUnit.MILLISECONDS)\r\n@Fork(1)\r\n@Warmup(iterations = 2)\r\n@Measurement(iterations = 5)\r\npublic class RegexpBenchmark {\r\n    private static final int ITERATIONS_COUNT = 1000;\r\n    @State(Scope.Benchmark)\r\n    public static class BenchmarkState {\r\n        String testString = &quot;*example*text**with*many*asterisks**&quot;.repeat(ITERATIONS_COUNT);\r\n    }\r\n    @Benchmark\r\n    public void backReference(BenchmarkState state) {\r\n        state.testString.replaceAll(&quot;(^\\\\*)|(\\\\*$)|\\\\*&quot;, &quot;$1$2&quot;);\r\n    }\r\n    @Benchmark\r\n    public void lookaround(BenchmarkState state) {\r\n        state.testString.replaceAll(&quot;(?&lt;!^)\\\\*+(?!$)&quot;, &quot;&quot;);\r\n    }\r\n    public static void main(String[] args) throws Exception {\r\n        Options opt = new OptionsBuilder().include(RegexpBenchmark.class.getSimpleName())\r\n          .build();\r\n        new Runner(opt).run();\r\n    }\r\n}<\/code><\/pre>\n<p>The resulting output of this example states clearly that the lookaround method is more performant:<\/p>\n<pre><code class=\"language-shell\">Benchmark                      Mode  Cnt  Score   Error  Units\r\nRegexpBenchmark.backReference  avgt    5  0.504 \u00b1 0.011  ms\/op\r\nRegexpBenchmark.lookaround     avgt    5  0.315 \u00b1 0.006  ms\/op<\/code><\/pre>\n<p>So, <strong>back reference is slower because it requires an overhead to capture the groups individually and then replace those groups with the replacement string<\/strong>. While lookaround, as explained previously, selects the characters directly and removes them.<\/p>\n<h2 id=\"bd-conclusion\" data-id=\"conclusion\">5. Conclusion<\/h2>\n<div class=\"bd-anchor\" id=\"conclusion\"><\/div>\n<p>In this article, we saw how to use the <em>replaceAll()<\/em> method with back references and lookarounds in regular expressions. While back references are useful for reusing parts of the matched string, they can be slower due to the overhead of capturing groups. To demonstrate this, we performed a benchmark to compare the two methods.<\/p>\n<p>As always, we can check the complete code <a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/github.com\/eugenp\/tutorials\/tree\/master\/core-java-modules\/core-java-regex-3\">over on GitHub<\/a>.<\/p>\n<p><Img align=\"left\" border=\"0\" height=\"1\" width=\"1\" alt=\"\" style=\"border:0;float:left;margin:0;padding:0;width:1px!important;height:1px!important;\" hspace=\"0\" src=\"https:\/\/feeds.feedblitz.com\/~\/i\/897342410\/0\/baeldung\"><\/p>\n<div style=\"clear:both;padding-top:0.2em;\"><a title=\"Like on Facebook\" href=\"https:\/\/feeds.feedblitz.com\/_\/28\/897342410\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/fblike20.png\" style=\"border:0;margin:0;padding:0;\"><\/a>&#160;<a title=\"Pin it!\" href=\"https:\/\/feeds.feedblitz.com\/_\/29\/897342410\/baeldung,https%3A%2F%2Fwww.baeldung.com%2Fwp-content%2Fuploads%2F2016%2F10%2Fsocial-Java-On-Baeldung-2.jpg\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/pinterest20.png\" style=\"border:0;margin:0;padding:0;\"><\/a>&#160;<a title=\"Post to X.com\" href=\"https:\/\/feeds.feedblitz.com\/_\/24\/897342410\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/x.png\" style=\"border:0;margin:0;padding:0;\"><\/a>&#160;<a title=\"Subscribe by email\" href=\"https:\/\/feeds.feedblitz.com\/_\/19\/897342410\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/email20.png\" style=\"border:0;margin:0;padding:0;\"><\/a>&#160;<a title=\"Subscribe by RSS\" href=\"https:\/\/feeds.feedblitz.com\/_\/20\/897342410\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/rss20.png\" style=\"border:0;margin:0;padding:0;\"><\/a>&#160;<a rel=\"NOFOLLOW\" title=\"View Comments\" href=\"https:\/\/www.baeldung.com\/java-regex-replace-strings-back-reference-vs-lookaround#respond\"><img decoding=\"async\" height=\"20\" style=\"border:0;margin:0;padding:0;\" src=\"https:\/\/assets.feedblitz.com\/i\/comments20.png\"><\/a>&#160;<a title=\"Follow Comments via RSS\" href=\"https:\/\/www.baeldung.com\/java-regex-replace-strings-back-reference-vs-lookaround\/feed\"><img decoding=\"async\" height=\"20\" style=\"border:0;margin:0;padding:0;\" src=\"https:\/\/assets.feedblitz.com\/i\/commentsrss20.png\"><\/a>&#160;<\/div>\n\n<p class=\"syndicated-attribution\"><figure class= \\\"wp-block-image alignnone \\\"><img src= \\\"http:\/\/itteacheritfreelance.hk\/test\/wordpress\/wp-content\/uploads\/2016\/05\/logo2-2.png\\\" alt=\\\"IT\u96fb\u8166\u88dc\u7fd2 java\u88dc\u7fd2 \u70ba\u5927\u5bb6\u914d\u5c0d\u96fb\u8166\u88dc\u7fd2,IT freelance, \u79c1\u4eba\u8001\u5e2b, PHP\u88dc\u7fd2,CSS\u88dc\u7fd2,XML,Java\u88dc\u7fd2,MySQL\u88dc\u7fd2,graphic design\u88dc\u7fd2,\u4e2d\u5c0f\u5b78ICT\u88dc\u7fd2,\u4e00\u5c0d\u4e00\u79c1\u4eba\u88dc\u7fd2\u548cFreelance\u81ea\u7531\u5de5\u4f5c\u914d\u5c0d\u3002\\\"\/><figcaption>\u7acb\u523b\u8a3b\u518a\u53ca\u5831\u540d\u96fb\u8166\u88dc\u7fd2\u8ab2\u7a0b\u5427!<\/figcaption><\/figure>\r\n<\/br>Find A Teacher Form:\r\n<\/br>https:\/\/docs.google.com\/forms\/d\/1vREBnX5n262umf4wU5U2pyTwvk9O-JrAgblA-wH9GFQ\/viewform?edit_requested=true#responses\r\n<\/br><\/br>Email:\r\n<\/br>public1989two@gmail.com<br><br><br><br><br><br><br>\r\n<a href=www.itsec.hk style=color:#FFFFFF;>www.itsec.hk<\/a><br>\r\n<a href=\\\"www.itsec.vip\\\" style=color:#FFFFFF;>www.itsec.vip<\/a><br>\r\n<a href=\\\"www.itseceu.uk\\\" style=color:#FFFFFF;>www.itseceu.uk<\/a><br><\/p>","protected":false},"excerpt":{"rendered":"<div class=\"mh-excerpt\"><p><img decoding=\"async\" src=\"https:\/\/www.baeldung.com\/wp-content\/uploads\/2016\/10\/social-Java-On-Baeldung-2.jpg\" class=\"webfeedsFeaturedVisual wp-post-image\" alt=\"\"><\/p>\n<p>In this tutorial, we&#8217;ll explore how to use the replaceAll() method in the String class to replace text using regular expressions. We&#8217;ll compare the back reference and lookaround methods for this operation and evaluate their performance.<\/p>\n<div><a title=\"Like on Facebook\" href=\"https:\/\/feeds.feedblitz.com\/_\/28\/897342410\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/fblike20.png\"><\/a>\u00a0<a title=\"Pin it!\" href=\"https:\/\/feeds.feedblitz.com\/_\/29\/897342410\/baeldung,https%3A%2F%2Fwww.baeldung.com%2Fwp-content%2Fuploads%2F2016%2F10%2Fsocial-Java-On-Baeldung-2.jpg\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/pinterest20.png\"><\/a>\u00a0<a title=\"Post to X.com\" href=\"https:\/\/feeds.feedblitz.com\/_\/24\/897342410\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/x.png\"><\/a>\u00a0<a title=\"Subscribe by email\" href=\"https:\/\/feeds.feedblitz.com\/_\/19\/897342410\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/email20.png\"><\/a>\u00a0<a title=\"Subscribe by RSS\" href=\"https:\/\/feeds.feedblitz.com\/_\/20\/897342410\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/rss20.png\"><\/a>\u00a0<a rel=\"NOFOLLOW\" title=\"View Comments\" href=\"https:\/\/www.baeldung.com\/java-regex-replace-strings-back-reference-vs-lookaround#respond\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/comments20.png\"><\/a>\u00a0<a title=\"Follow Comments via RSS\" href=\"https:\/\/www.baeldung.com\/java-regex-replace-strings-back-reference-vs-lookaround\/feed\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/commentsrss20.png\"><\/a>\u00a0<\/div>\n<\/div>","protected":false},"author":2058,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"slim_seo":{"title":"Replacing Strings in Java Using Regex: Back Reference vs. Lookaround - ITTeacherITFreelance.hk","description":"In this tutorial, we'll explore how to use the replaceAll() method in the String class to replace text using regular expressions. We'll compare the back referen"},"footnotes":""},"categories":[6,1307],"tags":[],"_links":{"self":[{"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/posts\/329569"}],"collection":[{"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/users\/2058"}],"replies":[{"embeddable":true,"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/comments?post=329569"}],"version-history":[{"count":1,"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/posts\/329569\/revisions"}],"predecessor-version":[{"id":329570,"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/posts\/329569\/revisions\/329570"}],"wp:attachment":[{"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/media?parent=329569"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/categories?post=329569"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/tags?post=329569"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}