Java regex replace groups

Java Regex — Replacement Operations

java.util.regex.Matcher defines followings methods for replacing matched substrings with new strings.

Append and Replace Operation

This is a multi-steps operation. It basically appends the unmatched parts of the input string to a provided StringBuffer instance and at the same time replaces the matched parts with the provided replacement string and then appends to the same StringBuffer object. Here are two methods we have to be familiar with.

  1. StringBuffer appendReplacement(StringBuffer sb, String replacement) : This method first appends the input string to the provided StringBuffer starting from end index position of the last match (if there’s no last match then starts from 0 index) to the current match position, given by matcher#start() . Second thing this method does is to append the replacement string instead of the current match.
  2. StringBuffer appendTail(StringBuffer sb) : This is the very last method to be called during ‘append-and-replace’ operation. It is called only once. It appends the remaining unmatched part of the input string to the provided StringBuffer .

Example:

Pattern p = Pattern.compile("\\b\\d+\\b"); Matcher m = p.matcher("There are 200 items in 500 boxes."); StringBuffer sb = new StringBuffer(); while (m.find()) < m.appendReplacement(sb, "multiple"); >m.appendTail(sb); System.out.println(sb.toString());
/*Regex breakdown: \\b\\d+\\b
\\bThe word boundary.
\\d+One or more digits.
\\bThe word boundary.

*/

Output

There are multiple items in multiple boxes.

Other Methods

  1. Matcher#replaceAll(String replacement) : Replaces every match (given by matcher#group() or matcher#group(0)) of the input string with the provided replacement string:
Читайте также:  Java web start jnlp file

Example:

Pattern p = Pattern.compile("\\b\\d+\\b"); Matcher m = p.matcher("There are 200 items in 500 boxes."); String s = m.replaceAll("multiple"); System.out.println(s);
/*Regex breakdown: \\b\\d+\\b
\\bThe word boundary.
\\d+One or more digits.
\\bThe word boundary.

*/

Output

There are multiple items in multiple boxes.

Example

Pattern p = Pattern.compile("\\b\\d+\\b"); Matcher m = p.matcher("There are 200 items in 500 boxes."); String s = m.replaceFirst("multiple"); System.out.println(s);
/*Regex breakdown: \\b\\d+\\b
\\bThe word boundary.
\\d+One or more digits.
\\bThe word boundary.

*/

Output

There are multiple items in 500 boxes.

java.lang.String Equivalents

  1. String#replaceAll is equivalent to matcher#replaceAll. That is String’s replaceAll creates a Matcher instance in the background
  2. String#replaceFirst is equivalent to matcher#replaceFirst.

Example Project

Dependencies and Technologies Used:

Источник

Java Regex — Capturing Group Reference in Replacement String

The capturing groups can be referenced in the matcher’s replacement string.

Syntax:

  1. $ : Using capturing group name ‘groupName’. We must have defined the group name in the regex.
  2. $groupNumber : if we want to use group number instead of group name. May be we don’t have related group name defined in the regex.

Examples:

Asume our example input string contains some sort of alphanumeric code with this format: a alphabet followed by two digits. We want to use java regex to interchange their positions i.e. the two digits followed by the alphabet.

/* Using capturing group name*/ Pattern.compile("(?[a-z])(?7)") 
.matcher("a38 d45")
.replaceAll("$$");//result: '38a 45d'
/*Regex breakdown: (?[a-z])(?5)
(Starting the first capturing group.
? Giving name to this capturing group: 'aCode.'
[a-z] Must contain exactly one alphabet.
)Closing the first capturing group.
(Start the second capturing group.
? Giving name to this capturing group: 'dCode'.
2 Must contain exactly two digits.
)Closing the second group.

*/ /* Using capturing group number*/ Pattern.compile("([a-z])(5)")
.matcher("a38 d45")
.replaceAll("$2$1");//result: '38a 45d'
/*Regex breakdown: ([a-z])(8)
(Starting the first capturing group.
[a-z] Must contain exactly one alphabet.
)Closing the first capturing group.
(Start the second capturing group.
5 Must contain exactly two digits.
)Closing the second group.

*/

It’s important to know that if we want to use $ in the replacement string as a literal, we have to escape it with a double backslashes i.e. \\$ . Also we should always escape a single slash \ in the replacement string i.e. \\\\ .

Example Project

Dependencies and Technologies Used:

Источник

Java Regular Expressions Group Replace

We can use the group in regular expressions to format text.

For example, we can replace all 10-digit phone numbers in the input text by formatted phone numbers.

In order to replace matched text we can use the replaceAll() method of the String class.

Or we can use the replaceAll() method from Matcher class.

$n, where n is a group number, inside replacement text refers to the matched text for group n.

For example, $1 refers to the first matched group.

The replacement text to replace the phone numbers with the formatted phone numbers will be ($1) $2-$3.

Example

The following code references groups in replacement text.

import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main < public static void main(String[] args) < // Prepare the regular expression String regex = "\\b(\\d)(\\d)(\\d)\\b"; String replacementText = "($1) $2-$3"; String source = "1234567890, 1234567, and 0987654321"; // Compile the regular expression Pattern p = Pattern.compile(regex); // Get Matcher object Matcher m = p.matcher(source); // Replace the phone numbers by formatted phone numbers String formattedSource = m.replaceAll(replacementText); System.out.printf("Text: %s%n", source ); System.out.printf("Formatted Text: %s%n", formattedSource ); > /*w w w . d e m o2 s . c o m */ >

We can also achieve the same result by using the String class without using the Pattern and Matcher classes at all.

Example 2

The following snippet of code illustrates how to use the String class to replace formated phone numbers.

The String class uses Pattern and Matcher class internally to get the result.

public class Main < public static void main(String[] args) < // Prepare the regular expression String regex = "\\b(\\d)(\\d)(\\d)\\b"; String replacementText = "($1) $2-$3"; String source = "1234567890, 1234567, and 0987654321"; // Use replaceAll() method of the String class String formattedSource = source.replaceAll(regex, replacementText) ; System.out.println(formattedSource); > >

  • Java Regular Expressions Back reference group
  • Java Regular Expressions Group match
  • Java Regular Expressions Group Format
  • Java Regular Expressions Group Replace
  • Java Regular Expressions Named Groups
  • Java Regular Expressions Group Boundary
  • Java Regular Expression Review Question 1

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

Источник

Оцените статью