

{"id":126628,"date":"2024-07-09T18:00:06","date_gmt":"2024-07-09T12:30:06","guid":{"rendered":"https:\/\/data-flair.training\/blogs\/?p=126628"},"modified":"2026-05-18T12:20:35","modified_gmt":"2026-05-18T06:50:35","slug":"java-string-replaceall-method","status":"publish","type":"post","link":"https:\/\/data-flair.training\/blogs\/java-string-replaceall-method\/","title":{"rendered":"Java String replaceAll() Method with Examples"},"content":{"rendered":"<p>The replaceAll() method in Java&#8217;s String class is a helpful tool for changing parts of a text. In this article, we&#8217;ll take a closer look at how to use this method with simple examples. It&#8217;s a useful method for modifying text.<\/p>\n<p>The Java replaceAll() method works by looking for a specific pattern (a regular expression or regex) in the text and replacing it with something else. We&#8217;ll show you the basic structure of how it&#8217;s used and then give you some practical examples to make it clear.<\/p>\n<p>Whether you&#8217;re a Java developer or just someone interested in learning, this article will make it easy for you to understand how replaceAll() can be a valuable tool for text manipulation in Java.<\/p>\n<h3>Some key points about Java replaceAll()<\/h3>\n<ul>\n<li>It replaces all occurrences of the matched regex, not just the first match.<\/li>\n<li>The replacement string can contain capturing groups from the regex to insert partial matches.<\/li>\n<li>It returns a new string with replacements, not modifying the original.<\/li>\n<\/ul>\n<h3>Syntax and Parameters of Java replaceAll()<\/h3>\n<p><strong>The basic syntax of using Java replaceAll() is:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">String replaced = original.replaceAll(regex, replacement);<\/pre>\n<p><strong>Where:<\/strong><\/p>\n<ul>\n<li><strong>original &#8211;<\/strong> The original string<\/li>\n<li><strong>regex &#8211;<\/strong> The regular expr. to match<\/li>\n<li><strong>replacement &#8211;<\/strong> The string to replace matches<\/li>\n<\/ul>\n<p>The method returns a new string with all matches of the regex replaced.<\/p>\n<p><strong>Example of\u00a0 Java replaceAll()<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">public class StringReplaceExample {\r\n    public static void main(String[] args) {\r\n        String str = \"Hello World\";\r\n        String result = str.replaceAll(\"l\", \"w\");\r\n\r\n        System.out.println(result);\r\n    }\r\n}<\/pre>\n<p><strong>Output:<\/strong><br \/>\nHewwo Wod<\/p>\n<p>The regular expression &#8220;l&#8221; matches all occurrences of the letter &#8216;l&#8217;, which are then replaced with &#8220;w&#8221;.<\/p>\n<h3>Capturing Groups Example<\/h3>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">public class StringReplaceExample {\r\n    public static void main(String[] args) {\r\n        String str = \"Hello World\";\r\n        str = str.replaceAll(\"(\\\\w+) (\\\\w+)\", \"$2, $1\");\r\n\r\n        System.out.println(str);\r\n    }\r\n}<\/pre>\n<p><strong>Output:<\/strong><br \/>\nWorld, Hello<\/p>\n<h3>Common Exceptions<\/h3>\n<p>Two common exceptions may occur when using the replaceAll() method incorrectly:<\/p>\n<h4>PatternSyntaxException in Java<\/h4>\n<p>This exception is thrown when the regular expression passed to replaceAll() is invalid. The Java regular expression engine will fail to compile the invalid regex pattern, resulting in a PatternSyntaxException being thrown.<\/p>\n<p><strong>Example of<\/strong><\/p>\n<h4>PatternSyntaxException in Java<strong>:<\/strong><\/h4>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">public class StringReplaceExample {\r\n    public static void main(String[] args) {\r\n        String str = \"Hello\";\r\n        String regex = \"[a-z\"; \/\/ Missing closing ] makes this an invalid regex\r\n\r\n        try {\r\n            str = str.replaceAll(regex, \"X\");\r\n        } catch (java.util.regex.PatternSyntaxException e) {\r\n            System.out.println(\"PatternSyntaxException: \" + e.getMessage());\r\n        }\r\n    }\r\n}<\/pre>\n<p><strong>Output:<\/strong><br \/>\nPatternSyntaxException: Unclosed character class near index 4<br \/>\n[a-z<br \/>\n^<\/p>\n<p><strong>Some common causes of invalid regex patterns include:<\/strong><\/p>\n<ul>\n<li>Unescaped special characters<\/li>\n<li>Unclosed character classes and groups<\/li>\n<li>Quantifiers applied to invalid tokens<\/li>\n<li>Invalid repetition syntax<\/li>\n<li>Incorrect escaping of reserved characters<\/li>\n<\/ul>\n<h4>NullPointerException in Java<\/h4>\n<p>This exception occurs when a null value is passed as the regular expression parameter to replaceAll().<\/p>\n<p><strong>Example of NullPointerException in Java:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">public class StringReplaceExample {\r\n    public static void main(String[] args) {\r\n        String str = \"World\";\r\n\r\n        try {\r\n            str = str.replaceAll(null, \"X\"); \/\/ Passing null regex causes NullPointerException\r\n        } catch (NullPointerException e) {\r\n            System.out.println(\"NullPointerException: \" + e.getMessage());\r\n        }\r\n    }\r\n}<\/pre>\n<p><strong>Output:<\/strong><br \/>\n<strong>NullPointerException:<\/strong> Regular expression is null<\/p>\n<p>The replaceAll() method expects a valid, non-null regex pattern. Passing null will result in a NullPointerException being thrown.<\/p>\n<p>This is because replaceAll() attempts to access methods on the regex object to perform the replacements. When null is passed instead of a Regex object, it results in a null pointer dereference.<\/p>\n<p>To avoid this, always pass a properly initialized regular expression string or Regex object to replaceAll().<\/p>\n<h3><strong>Advantages of replaceAll() in Java<\/strong><\/h3>\n<ul>\n<li>This method performs better in replacing the regex pattern.<\/li>\n<li>The replaceAll() method is preferred over the replace method for operating on complex data.<\/li>\n<li>It works on all the occurrences at one time, calling.<\/li>\n<\/ul>\n<h3>Disadvantages of replaceAll() in Java<\/h3>\n<ul>\n<li>It consumes a large amount of memory when used for complex data.<\/li>\n<li>replaceAll() has slower execution.<\/li>\n<\/ul>\n<h3>Conclusion<\/h3>\n<p>In conclusion, the replaceAll() method in Java&#8217;s String class is a powerful tool for replacing specified substrings in a string using regular expressions.<\/p>\n<p>Key points to remember include its ability to replace all occurrences of a matched regex, support for capturing groups for partial matches, and the creation of a new string with replacements while leaving the original unchanged.<\/p>\n<p>It is important to handle common exceptions such as PatternSyntaxException, which occurs when an invalid regex is used, and NullPointerException, which arises when a null value is passed as the regular expression. To ensure smooth usage, always provide a valid and non-null regex pattern.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>The replaceAll() method in Java&#8217;s String class is a helpful tool for changing parts of a text. In this article, we&#8217;ll take a closer look at how to use this method with simple examples.&#46;&#46;&#46;<\/p>\n","protected":false},"author":86671,"featured_media":134337,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[32],"tags":[7345,31236,31231,31234,31078,8152,31235,31237,31233,31232],"class_list":["post-126628","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java","tag-java","tag-java-replaceall-method","tag-java-string-replaceall-method","tag-java-string-replaceall-method-with-examples","tag-java-tutorials","tag-learn-java","tag-replaceall-method","tag-replaceall-method-in-java","tag-string-replaceall-method","tag-string-replaceall-method-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 String replaceAll() Method with Examples - DataFlair<\/title>\n<meta name=\"description\" content=\"replaceAll() method in Java&#039;s String class is a powerful tool for replacing specified substrings in a string using regular expressions.\" \/>\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-string-replaceall-method\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Java String replaceAll() Method with Examples - DataFlair\" \/>\n<meta property=\"og:description\" content=\"replaceAll() method in Java&#039;s String class is a powerful tool for replacing specified substrings in a string using regular expressions.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/data-flair.training\/blogs\/java-string-replaceall-method\/\" \/>\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=\"2024-07-09T12:30:06+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2026-05-18T06:50:35+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/11\/java-string-replacell90.webp\" \/>\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\/webp\" \/>\n<meta name=\"author\" content=\"TechVidvan 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=\"TechVidvan Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"3 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Java String replaceAll() Method with Examples - DataFlair","description":"replaceAll() method in Java's String class is a powerful tool for replacing specified substrings in a string using regular expressions.","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-string-replaceall-method\/","og_locale":"en_US","og_type":"article","og_title":"Java String replaceAll() Method with Examples - DataFlair","og_description":"replaceAll() method in Java's String class is a powerful tool for replacing specified substrings in a string using regular expressions.","og_url":"https:\/\/data-flair.training\/blogs\/java-string-replaceall-method\/","og_site_name":"DataFlair","article_publisher":"https:\/\/www.facebook.com\/DataFlairWS\/","article_published_time":"2024-07-09T12:30:06+00:00","article_modified_time":"2026-05-18T06:50:35+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/11\/java-string-replacell90.webp","type":"image\/webp"}],"author":"TechVidvan Team","twitter_card":"summary_large_image","twitter_creator":"@DataFlairWS","twitter_site":"@DataFlairWS","twitter_misc":{"Written by":"TechVidvan Team","Est. reading time":"3 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/data-flair.training\/blogs\/java-string-replaceall-method\/#article","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/java-string-replaceall-method\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/0e594f928e31fc96628ac40f6ae74f49"},"headline":"Java String replaceAll() Method with Examples","datePublished":"2024-07-09T12:30:06+00:00","dateModified":"2026-05-18T06:50:35+00:00","mainEntityOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/java-string-replaceall-method\/"},"wordCount":603,"commentCount":0,"publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/java-string-replaceall-method\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/11\/java-string-replacell90.webp","keywords":["Java","java replaceAll() method","java string replaceAll() method","java string replaceAll() method with examples","java tutorials","Learn Java","replaceAll() method","replaceAll() method in java","string replaceAll() method","string replaceAll() method in java"],"articleSection":["Java Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/data-flair.training\/blogs\/java-string-replaceall-method\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/data-flair.training\/blogs\/java-string-replaceall-method\/","url":"https:\/\/data-flair.training\/blogs\/java-string-replaceall-method\/","name":"Java String replaceAll() Method with Examples - DataFlair","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/#website"},"primaryImageOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/java-string-replaceall-method\/#primaryimage"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/java-string-replaceall-method\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/11\/java-string-replacell90.webp","datePublished":"2024-07-09T12:30:06+00:00","dateModified":"2026-05-18T06:50:35+00:00","description":"replaceAll() method in Java's String class is a powerful tool for replacing specified substrings in a string using regular expressions.","breadcrumb":{"@id":"https:\/\/data-flair.training\/blogs\/java-string-replaceall-method\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/data-flair.training\/blogs\/java-string-replaceall-method\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/java-string-replaceall-method\/#primaryimage","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/11\/java-string-replacell90.webp","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/11\/java-string-replacell90.webp","width":1200,"height":628,"caption":"java string replaceall"},{"@type":"BreadcrumbList","@id":"https:\/\/data-flair.training\/blogs\/java-string-replaceall-method\/#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 String replaceAll() Method 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\/0e594f928e31fc96628ac40f6ae74f49","name":"TechVidvan Team","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/c89190da3d4010c71ba476b618ab10fdc2335c82cdfa0ad5002d98d0f2473444?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/c89190da3d4010c71ba476b618ab10fdc2335c82cdfa0ad5002d98d0f2473444?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/c89190da3d4010c71ba476b618ab10fdc2335c82cdfa0ad5002d98d0f2473444?s=96&d=mm&r=g","caption":"TechVidvan Team"},"description":"TechVidvan Team provides high-quality content &amp; courses on AI, ML, Data Science, Data Engineering, Data Analytics, programming, Python, DSA, Android, Flutter, full stack web dev, MERN, and many latest technology.","url":"https:\/\/data-flair.training\/blogs\/author\/test001\/"}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/126628","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\/86671"}],"replies":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/comments?post=126628"}],"version-history":[{"count":6,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/126628\/revisions"}],"predecessor-version":[{"id":148331,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/126628\/revisions\/148331"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media\/134337"}],"wp:attachment":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media?parent=126628"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/categories?post=126628"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/tags?post=126628"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}