search
HomeJavajavaTutorialreplaceAll() in Java
replaceAll() in JavaAug 30, 2024 pm 03:38 PM
java

ReplaceAll() is the method of String class which replaces all the occurrence of character which matching with the parameters it takes, all the substring will get replaced by the input we pass to the method as a regular expression and replacement of the given staring this method will return us String object. It is present inside the String class (java.lang.String) this package. In this topic, we are going to learn about replaceAll() in Java.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Syntax with parameters

public String replaceAll(String regex, String replacement)

Above is the method signature for the replaceAll() method. This can be used directly in our code because of the java in build method provided by the String class. It takes two parameters as input :

  • regex(Regular expression): This input is used to match in the given string.
  • replacement: This is used as a string we want at the place of the above-matched string. This is the new content or string we can say that we want to see as output.

This method will always return the string object. One more thing, the regular expression uses a pattern also, which we will discuss below.

Resulting String: As Output

How does the replaceAll() method work in Java?

replaceAll is the method that is present in the String class. It takes two parameters as input, i.e. regular expression and replacement. As the name suggests, it is used to replace some part of a string or the whole string.

This method throws the exception mentioned below :

1. PatternSyntaxException

This exception is the unchecked exception in java which will only occur if there is an error in the regular expression we pass in the method as the input parameter. Like other class it has some predefined or in-build method which helps us to identify the issue:

  • public String getMessage(): This method contains the description of the exception.
  • public int getIndex(): This method is going to return the index for the error.
  • public String getPattern(): This method will provide us with the regular expression which contains the error.
  • public String getDescription(): This method will provide us with decryption with respect to the error.

2. Regular expression detail

The regular expression that we are passing as a string into the method parameter, but this regular expression is the pattern class’s compiled instance. it is present in java.util.regex.Pattern package.

This regular expression contains the following things :

  • Pattern
  • Matchers

we also have a matcher method in this. It complies with our regular expression.

  • t: for tab
  • a: for alert
  • cx: control character
  • e: escapecharacter
  • n: newline
  • f: form-feed

3. Methods available

  • split(CharSequence input): This method returns us string[] (string array) and takes input on behalf of we want to split.
  • split(CharSequence input, int limit): works in the same way, but this method also takes a limit parameter.
  • static Pattern compile(String regex, int flags): This method takes two parameters, regular expression and flag and compiles our regular expression.
  • 4) String pattern()
  • 5) static String quote(String s)

This pattern class also implements the Serializable Interface.

In this way, replaceAll works in java. It uses patterns and matches internally to compile the regular expression and for other operations.

Examples of replaceAll() in Java

Below are some examples to show how we can use it to replace a single character, whole string matching with regular expression, remove white spaces from the complete string, and replace string with the special character.

Example #1

In this example, we are passing regular expression as (.*)java(.*) this to replace the whole string whose substring is java from starting and end.

Code:

import java.io.*;
public class DemoReg {
public static void main(String args[]) {
String str = new String("Example to show replace in java string.");
System.out.print("Resulted string after replace is  :" );
System.out.println(str.replaceAll("(.*)java(.*)", "replaced"));
}
}

Output:

replaceAll() in Java

Example #2

In this example, we are replacing the part of a string with a special character. It means we can pass anything which can be treated as a string. we can pass numbers also.

Code:

public class DemoReg {
public static void main(String args[]) {
String s1="In this we are going to replace the string with some character. (repeat sequence)";
String str=s1.replaceAll("t*"," ***** ");
System.out.println("Ouptut is ::: ");
System.out.println(str);
}
}

Output:

replaceAll() in Java

Example #3

In this java class, we are replacing some part of the string with some other content. Example: “replacement done successfully” this in our case.

Code:

public class DemoReg {
public static void main(String args[]) {
String str="Now the demo is for replacing string with some another substring";
String result=str.replaceAll("string"," replacement done successfully");
System.out.println("Result after replace is :::: ");
System.out.println(result);
}
}

Output:

replaceAll() in Java

Example #4

In this example, we are trying to remove the spaces which are present in the given string. We have so many keywords with slashes (“\\”) that can be used to perform the given string’s operation.

Code:

public class DemoReg {
public static void main(String args[]) {
String str="Now we are going to replace the spaces present in the given string.";
System.out.println("String before replace performed :::: ");
System.out.println(str);
String result=str.replaceAll("\\s","");
System.out.println("Result after replace is :::: ");
System.out.println(result);
}
}

Output:

replaceAll() in Java

Example #5

In this java example, we are replacing the string with a single character only. It means when the given character appears in the string each time, it will be replaced by the method.

Code:

public class DemoReg {
public static void main(String args[]) {
String str="Replacing single character from the whole string demo.";
System.out.println("String before replace performed :::: ");
System.out.println(str);
String result=str.replaceAll("e"," X");
System.out.println("Result after replace is :::: ");
System.out.println(result);
}
}

Output:

replaceAll() in Java

We can have anything in the replacement, which is a string. But our regular expression has to be valid; otherwise, it will throw an unchecked exception for error containing regular expression in the replaceAll() method.

Conclusion

Replace method is the string class method of java, which takes two parameters. Any type of regular expression we can pass in it will replace the string for us unless it matches. So the above example will give you an understanding that how we can use this.

The above is the detailed content of replaceAll() in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
带你搞懂Java结构化数据处理开源库SPL带你搞懂Java结构化数据处理开源库SPLMay 24, 2022 pm 01:34 PM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于结构化数据处理开源库SPL的相关问题,下面就一起来看一下java下理想的结构化数据处理类库,希望对大家有帮助。

Java集合框架之PriorityQueue优先级队列Java集合框架之PriorityQueue优先级队列Jun 09, 2022 am 11:47 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于PriorityQueue优先级队列的相关知识,Java集合框架中提供了PriorityQueue和PriorityBlockingQueue两种类型的优先级队列,PriorityQueue是线程不安全的,PriorityBlockingQueue是线程安全的,下面一起来看一下,希望对大家有帮助。

完全掌握Java锁(图文解析)完全掌握Java锁(图文解析)Jun 14, 2022 am 11:47 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于java锁的相关问题,包括了独占锁、悲观锁、乐观锁、共享锁等等内容,下面一起来看一下,希望对大家有帮助。

一起聊聊Java多线程之线程安全问题一起聊聊Java多线程之线程安全问题Apr 21, 2022 pm 06:17 PM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于多线程的相关问题,包括了线程安装、线程加锁与线程不安全的原因、线程安全的标准类等等内容,希望对大家有帮助。

详细解析Java的this和super关键字详细解析Java的this和super关键字Apr 30, 2022 am 09:00 AM

本篇文章给大家带来了关于Java的相关知识,其中主要介绍了关于关键字中this和super的相关问题,以及他们的一些区别,下面一起来看一下,希望对大家有帮助。

Java基础归纳之枚举Java基础归纳之枚举May 26, 2022 am 11:50 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于枚举的相关问题,包括了枚举的基本操作、集合类对枚举的支持等等内容,下面一起来看一下,希望对大家有帮助。

java中封装是什么java中封装是什么May 16, 2019 pm 06:08 PM

封装是一种信息隐藏技术,是指一种将抽象性函式接口的实现细节部分包装、隐藏起来的方法;封装可以被认为是一个保护屏障,防止指定类的代码和数据被外部类定义的代码随机访问。封装可以通过关键字private,protected和public实现。

归纳整理JAVA装饰器模式(实例详解)归纳整理JAVA装饰器模式(实例详解)May 05, 2022 pm 06:48 PM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于设计模式的相关问题,主要将装饰器模式的相关内容,指在不改变现有对象结构的情况下,动态地给该对象增加一些职责的模式,希望对大家有帮助。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!