Java find and replace

Java Find-and-Replace Using Regular Expressions

We can use regular expressions to do find and replace actions on text.

With find and replace we can find a pattern and replace it depending upon the text it matches.

The Java regular expression included two methods in the Matcher class that we can use accomplish this task:

Matcher appendReplacement(StringBuffer sb, String replacement) Matcher appendReplacement(StringBuilder sb, String replacement) StringBuffer appendTail(StringBuffer sb) StringBuffer appendTail(StringBuilder sb)

The versions of the appendReplacement() and appendTail() methods that work with a StringBuilder were added in Java 9.

Example

Suppose we have the following text:

"I have 10 iphones. I have 12 computers. I have 5 ipads."

We want to find all numbers in the text and replace them as follows:

In order to do this we need to

  1. find all numbers embedded in the text,
  2. compare the found number with 10, and
  3. decide on the replacement text.

We can create a find/replace program using the two methods above.

Typically, these methods are used in conjunction with the find() method of the Matcher class.

Let’s create a Pattern by compiling the regular expression.

In order to find all numbers, the regular expression would be \b\d+\b.

The first and last \b. They specify that you are interested in numbers only on word boundaries.

String regex = "\\b\\d+\\b"; Pattern p = Pattern.compile(regex);

Create a Matcher by associating the pattern with the text.

String text = """ I have 10 iphones. I have 12 computers. I have 5 ipads."""; Matcher m = p.matcher(text);

We can prepare the replacement text depending on the matched text as:

String replacementText = ""; // Get the matched text. // group() method returns the whole matched text String matchedText = m.group(); // Convert the text into integer for comparison int num = Integer.parseInt(matchedText); // Prepare the replacement text if (num == 10) < replacementText = "ten"; > else if (num < 10) < replacementText = "less than ten"; > else < replacementText = "more than ten"; >

The complete source code to find and replace using Regular Expressions and appendReplacement() and appendTail() Methods.

import java.util.regex.Pattern; import java.util.regex.Matcher; public class Main < public static void main(String[] args) < String regex = "\\b\\d+\\b"; StringBuilder sb = new StringBuilder(); String text = """ I have 10 iphones. // w w w .d e m o2 s . c o m I have 12 computers. I have 5 ipads."""; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(text); while (m.find()) < String matchedText = m.group(); // Convert the text into an integer for comparing int num = Integer.parseInt(matchedText); // Prepare the replacement text String replacementText; if (num == 10) < replacementText = "ten"; > else if (num < 10) < replacementText = "less than ten"; > else < replacementText = "more than ten"; > m.appendReplacement(sb, replacementText); > // Append the tail m.appendTail(sb); // Display the old and new text System.out.printf("Old Text: %s%n", text); System.out.printf("New Text: %s%n", sb.toString()); > >

  • Java Regular Expressions Matcher class methods
  • Java Regular Expressions Matcher class replace methods Tutorial
  • Java Regular Expressions Resetting the Matcher
  • Java Find-and-Replace Using Regular Expressions
  • Java Regular Expressions Querying a Match by MatchResult
  • Java Streams of Matched Results from Regular Expressions
  • Java Regex group characters with parentheses

demo2s.com | Email: | Demo Source and Support. All rights reserved.

Источник

Search and replace with regular expressions

It is possible to perform search and replace operations on strings in Java using regular expressions. The Java String and Matcher classes offer relatively simple methods for matching and search/replacing strings which can bring the benefit of string matching optimisations that could be cumbersome to implement from scratch. The complexity of using these methods depends how much flexibility you need:

  • to find and replace instance of one fixed substring with another, we can use String.replaceAll()— we just need to take a little care (see below);
  • to search for and replace instances of a regular expression in a string with a fixed string, then we can generally use a simple call to String.replaceAll();
  • if the replacement string isn’t fixed, then you can use replaceAll() with a lambda expression to specify a dynamic replacement and/or use the Java Pattern and Matcher classes explicitly, giving complete control over the find and replace operation.

Replacing one «fixed» substring with another

This is the «simplest» form of search and replace. We want to find exact instances of a specific subtring and replace them with another given substring. To do so, we can call replaceAll() on the String, but we need to put Pattern.quote() around the substring we are searching for. For example, this will replace all instances of the substring «1+» with «one plus»:

str = str.replaceAll(Pattern.quote("1+"), "one plus");

If you are familiar with regular expressions, then you will know that a plus sign normally has a special meaning. But provided you remember to put Pattern.quote() around the first string, we can use replaceAll() as a simple search and replace call. (If the replacement substring contains a dollar sign or backslash, then we also need to use Matcher.quoteReplacement(): see below.)

Replacing substrings with a fixed string

If you simply want to replace all instances of a given expression within a Java string with another fixed string, then things are fairly straightforward. For example, the following replaces all instances of digits with a letter X:

We’ll see in the next section that we should be careful about passing «raw» strings as the second paramter, since certain characters in this string actually have special meanings.

Replacing with a sub-part of the matched portion

In the replacement string, we can refer to captured groups from the regular expression. For example, the following expression removes instances of the HTML ‘bold’ tag from a string, but leaves the text inside the tag intact:

In the expression ([^<]*), we capture the text between the open and close tags as group 1. Then, in the replacement string, we can refer to the text of group 1 with the expression $1. (The second group would be $2 etc.)

Including a dollar sign or backslashes in the replacement string

To actually include a dollar sign or backslash in the replacement string, we need to put another backslash before the dollar symbol or backslash to «escape» it. remembering that within a string literal, a single backslash also needs to be doubled up! For example:

The static method Matcher.quoteReplacement() will replace instances of dollar signs and backslashes in a given string with the correct form to allow them to be used as literal replacements:

str = str.replaceAll("USD", Matcher.quoteReplacement("$"));
  • If there is a chance that the replacement string will include a dollar sign or a backslash character, then you should wrap it in Matcher.quoteReplacement().

Further information: more flexible find and replacement operations

  • the replaceAll() method can be used with a lambda expression: see the accompanying page and example of using replaceAll() with a lambda expression;
  • Matcher.find() method can be used to provide further control over the operation.

If you enjoy this Java programming article, please share with friends and colleagues. Follow the author on Twitter for the latest news and rants. Follow @BitterCoffey

Editorial page content written by Neil Coffey. Copyright © Javamex UK 2021. All rights reserved.

Источник

How do I find and replace string?

The code below demonstrates the use Matcher.appendReplacement() and Matcher.appendTail() methods to create a program to find and replace a sub string within a string.

Another solution that can be used to search and replace a string can be found on the following example: How do I create a string search and replace using regex?.

package org.kodejava.regex; import java.util.regex.Matcher; import java.util.regex.Pattern; public class AppendReplacementExample < public static void main(String[] args) < // Create a Pattern instance Pattern pattern = Pattern.compile("[Pp]en"); // Create matcher object String input = "Please use your Pen to answer the question, " + "black pen is preferred."; Matcher matcher = pattern.matcher(input); StringBuilder builder = new StringBuilder(); // Find and replace the text that match the pattern while (matcher.find()) < matcher.appendReplacement(builder, "pencil"); >// This method reads characters from the input sequence, starting // at the beginning position, and appends them to the given string // builder. It is intended to be invoked after one or more // invocations of the appendReplacement method in order to copy // the remainder of the input sequence. matcher.appendTail(builder); System.out.println("Input : " + input); System.out.println("Output: " + builder); > > 

Here is the result of the above code:

Input : Please use your Pen to answer the question, black pen is preferred. Output: Please use your pencil to answer the question, black pencil is preferred. 

A programmer, recreational runner and diver, live in the island of Bali, Indonesia. Programming in Java, Spring, Hibernate / JPA. You can support me working on this project, buy me a cup of coffee ☕ every little bit helps, thank you 🙏

Источник

Читайте также:  Php system function call
Оцените статью