How to Replace a Pattern Using Regular Expression in Java


In this example, we can get the method to replace a pattern using regular expression. The regular string is compiled into a pattern object, and then a matching matcher is obtained, which can be used to perform a series of operations including judgment, acquisition and replacement.

Source Code

package com.beginner.examples;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ReplaceStringExample {

	public static void main(String[] args) {
		
		String reg = "[-=+]+";
		
		//Compiles the regular string into a Pattenr object
		Pattern pattern = Pattern.compile(reg);
		
		//Specifies the string to match to get the matcher
		Matcher matcher = pattern.matcher("The--man---with--a--new-idea-is-a+crank++until++the=idea==succeeds.");

		String string = matcher.replaceAll(" ");
		
		System.out.println(string);
	}
	
}

Ouput:

The man with a new idea is a crank until the idea succeeds.

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments