Home  >  Article  >  Java  >  replaceAll() in Java

replaceAll() in Java

王林
王林Original
2024-08-30 15:38:10572browse

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
Previous article:Java Stream FilterNext article:Java Stream Filter