How to Use Java String Class replaceFirst() Method

String replaceFirst() Method

Function Description

Java String Class replaceFirst() method is used to replace the first matching substring of the string with the specified replacement string which matches the given regular expression.

  • Backslashes and dollar signs in the replacement are not being treated as a literal replacement string. To replace these special characters we need to use a double backslash before it.

  • If the specified regular expression finds in the sting, It will return a string resulting from replacing the first matching sequence of characters

  • If the specified regular expression is not found in the sting, It will return the same string.

  • If the specified regex regular expression null, It will throw NullPointerException.

  • If the specified replacement string is null, It will throw NullPointerException.

  • If the specified regex is not valid it will throw PatrenSyntaxException

Trying to Explain all above points using the below methods.

  1. “reeplaceFirst method to reeplace first matching string”.replaceFirst(“reeplace“,”replace“) will return “replaceFirst method  to reeplace first matching string”

  2. “$reeplaceFirst method to reeplace first matching string”.replaceFirst(“\\$reeplace“,”replace“) will return “replaceFirst method  to reeplace first matching string”

  3. “\reeplaceFirst method to reeplace first matching string”.replaceFirst(“\\\reeplace“,”replace“) will return “replaceFirst method  to reeplace first matching string”

  4. “reeplaceFirst method to reeplace first matching string”.replaceFirst(“reeplacee”,”replace“) will return “reeplaceFirst method  to reeplace first matching string”

  5. “reeplaceFirst method to reeplace first matching string”.replaceFirst(null,”replace“) throws NullPointerException.

  6. “reeplaceFirst method to reeplace first matching string”.replaceFirst(“reeplacee “,null) throws NullPointerException.

String to be concatenated is “” blank, then returned concatenated string will be “Hello”

Method Signature

public String replaceFirst(String regex, String replacement)

Parameter(s)

Regex: regular expression to which the string will be matched to be replaced

Replacement: a sequence of characters (substring) to be replaced for the first match.

Return Type

It returns a string. If a regular expression matches, it returns a replaced string.

Exception

Throws PatternSyntaxException if regular expression is not valid

Examples of Java String Class replaceFirst() Method

Example to use Java Sting Class replaceFirst() in Java Code

package com.java.test;
 

public class ExampleStringReplaceFirst {
 
    public static void main(String[] args) {

          String str = "1234 RoundTheTech 1245 1256";

          System.out.println("Input String : " + str);

          System.out.println("");

          // replace only first occurrence of 12 with Hello

          String replacedString = str.replaceFirst("12", "Hello");

          System.out.println("After replace first occurrence of 12 with Hello : " + replacedString);
 
          // replace matched regular expression (match one or more time any digit range

          // 0-9) string with welcome string

          replacedString = str.replaceFirst("[0-9]+", "Welcome");

          System.out.println("Ater replacement string is : " + replacedString);
 

     }
}
 

Output:

Input String: 1234 RoundTheTech 1245 1256
 
After replace first occurrence of 12 with Hello: Hello34 RoundTheTech 1245 1256

Ater replacement string is: Welcome RoundTheTech 1245 1256

Example of Java code when PatternSyntaxException is thrown

public class ExampleStringReplaceFirst {
 
    public static void main(String[] args) {

          String str = "1234 RoundTheTech 1245 1256";
 
          String replacedString = str.replaceFirst("*", "Hello");

          System.out.println(replacedString);

     }

}


Output:

Exception in thread "main" java.util.regex.PatternSyntaxException: Dangling meta character '*' near index 0
*
^
    at java.util.regex.Pattern.error(Pattern.java:1957)

    at java.util.regex.Pattern.sequence(Pattern.java:2125)

    at java.util.regex.Pattern.expr(Pattern.java:1998)

    at java.util.regex.Pattern.compile(Pattern.java:1698)

    at java.util.regex.Pattern.<init>(Pattern.java:1351)

    at java.util.regex.Pattern.compile(Pattern.java:1028)

    at java.lang.String.replaceFirst(String.java:2178)

    at com.java.test.ExampleStringReplaceFirst.main(ExampleStringReplaceFirst.java:8)

Other Methods of String Class

SequenceMethodDescription
1char charAt(int index)This method is used to return the character of the string at specified index. First character is at index 0 while last is at string length-1 . StringIndexOutOfBounds Exception is thrown if valid index value is not passed.
2int length()Returns the number of characters count  in  a string.
3static String format(String format, Object… args)Return the formatted String. It is a static method and formats the string as per passing format and argument(s).
4static String format(Locale l, String format, Object… args)Return the formatted String. It is a static method and formats the string as per passing format and argument(s) and locale.
5String substring(int beginIndex)Returns substring from the given index position to the end index of the string.
6String substring(int beginIndex, int endIndex)Returns substring from the specified begin index to the specified end index.
7boolean contains(CharSequence s)Returns boolean value(true/false). It searches the given sequence of characters within the string and returns true/false accordingly. Characters will be case sensitive while searching in string.
8static String join(CharSequence delimiter, CharSequence… elements)Returns joined string. This method joins each passing String using the specified delimiter. It is a static method.
9static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements)Returns the joined string. This method joins each passing string object of an iterate object using the specified delimiter and returns the concatenated string. It is a static method.
10boolean equals(Object another)Returns boolean value(true/false). It checks the equality of string with the passing object.
11boolean isEmpty()Returns boolean value(true/false). It returns true if the string is empty otherwise returns false.
12String concat(String str)Returns the concatenating string. It concatenates the passing string at the end of the string.
13String replace(char old, char new)Return the replaced string. It replaces all occurrences of the specified character with the new character.
14String replace(CharSequence old, CharSequence new)Return the replaced string. It replaces all occurrences of the specified Character sequence with the specified new Character sequence.
15String replaceAll(String regex, String replacement)Returns the replaced string. It replaces all occurrences of the sequence of characters with the given replacement string that are matching with the given regular expression.
16static boolean equalsIgnoreCase(String another)Returns the boolean (true/false) value. It compares the passing string with string by ignoring the case. It  compares the content irrespective of lowercase or uppercase of the character(s).
17String[] split(String regex)Returns the array of strings resulting from splitting of the string     around matches of the given regular expression. String is breaked into strings from all  the matching regular expressions.
18String[] split(String regex, int limit)Returns the array of strings resulting from splitting of the string     around matches of the given regular expression. It breaks the string from all the matching regular expression upto the given limit.
19String intern()Returns an interned string. This method helps to compare two objects using == operator and checks in a string constant pool. it is faster for comparison.
20int indexOf(int ch)Returns the index value of first occurrence of the specified character within the string
21int indexOf(int ch, int fromIndex)Returns the index value of first occurrence of the specified character from the substring starting from specified index
22int indexOf(String substring)Returns the index value of first occurrence of the specified substring within the string.
23int indexOf(String substring, int fromIndex)Returns the index value of the first occurrence of the specified string within the substring starting from specified index to end of the string index.
24int lastIndexOf(int ch)Returns the index value of last occurrence of the specified character
25int lastIndexOf (int ch, int fromIndex)Returns the index value of last occurrence of the specified character, search starts at given fromIndex. 
26int lastIndexOf (String str)Returns the index value of last occurrence of the specified string.
27int lastIndexOf (String str, int fromIndexReturns the index value of last occurrence of the specified string, searches start from given fromIndex
28String toLowerCase()Returns all the characters of the string in lowercase .
29String toLowerCase(Locale l)Returns all the characters of the string in lowercase using specified locale.
30String toUpperCase()Returns all the characters of the string in uppercase.
31String toUpperCase(Locale l)Returns all the characters of the string in uppercase using specified locale.
32String trim()Returns the string after removing the white space from the beginning and end of the string.
33static String valueOf(int value)Return the converted string. It converts the objects and all primitive types of values into string. It is a static method.

In this article, we learned all about the replaceFirst() method of String class with examples. Apart from the replaceFirst() method we got an idea about other String methods too. We will come up with more articles explaining other String methods with examples .For more details please click on the respective methods link.

2 thoughts on “How to Use Java String Class replaceFirst() Method

  1. Wow, marvelous blog layout! How long have you been blogging for?

    you make blogging look easy. The overall look of your website is magnificent, as well as the content!

Leave a Reply

Your email address will not be published. Required fields are marked *