Replacing a part of the string that matches our given regular expression can be done using multiple methods.
As strings are immutable you cannot replace the pattern in the string itself instead, we will be creating a new string that stores the updated string.
1) replaceAll() Method
The method replaces all the occurrences of the pattern matched in the string.
Syntax:
Program to replace regular expression pattern in a string using replaceAll()
Output
2) replaceAllIn() Method
The method does the same work as replaceAll() but has a different syntax.
Syntax:
The function also returns an updated string with the matched pattern changed with the given replacestring.
Program to replace regular expression pattern in a string using replaceAllIn()
Output
3) replaceFirst() Method
The replaceFirst() method will replace the match pattern in the string but only at its first occurrence i.e. the match pattern will be replaced only at its first occurrence.
Syntax:
The function will return an updated string with the first matched pattern replaced with the given replace string.
Program to replace regular expression pattern in a string using replaceFirst()
Output
4) replaceFirstIn() Method
The replaceFirstIn() method will replace the match pattern in the string but only at its first occurrence i.e. the match pattern will be replaced only at its first occurrence.
The only difference is the syntax.
Syntax:
Program to replace regular expression pattern in a string using replaceFirstIn()
Output
need an explanation for this answer? contact us directly to get an explanation for this answer