![]() |
Regular Expressions (regex), in Java, are a tool, for searching, matching, and manipulating text patterns. Regex patterns are usually written as fixed strings. Based on different scenarios we may need to create a regex pattern based on a given string. In this article, we will learn how to replace a String using a regex pattern in Java. Step-by-step ImplementationStep 1: Import the java.util.regex packageimport java.util.regex.Pattern; Step 2: Define the regex pattern
Step 3: Create a Matcher object
Step 4: Apply the replacementProgram to Replace a String Using Regex Pattern in JavaMethod 1: Using replaceAll()In this example, we will replace string “12345” with “number” by using replaceAll() method. Java
Output
Original String: Hello, world! 12345 world. Modified String: Hello, world! number world. Explanation of the Program:
Method 2: By Using Matcher MethodsIn this example we will see how we can replace all “apple” with “orange” by using matcher methods. Java
Output
Original String: apple, banana, apple Modified String: orange, banana, orange Explanation of the Program:
|
Reffered: https://www.geeksforgeeks.org
Java |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 14 |