Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Matcher toString() method in Java with Examples
Next article icon

Matcher replaceFirst(String) Method in Java with Examples

Last Updated : 10 Nov, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

The replaceFirst() method of Matcher Class behaves as an append-and-replace method. This method reads the input string and replaces it with the first matched pattern in the matcher string. 

Syntax: 

public String replaceFirst(String stringToBeReplaced)

Parameters: The string to be replaced that is the String to be replaced in the matcher.

Return Type: A string with the target string constructed by replacing the string.

Example 1:

Java
// Java Program to Illustrate replaceFirst() Method // of Matcher class  // Importing required classes import java.util.regex.*;  // Main class public class GFG {      // Main driver method     public static void main(String[] args)     {         // Getting the regex to be checked         String regex = "(Geeks)";          // Creating a pattern from regex         Pattern pattern = Pattern.compile(regex);          // Getting the String to be matched         String stringToBeMatched             = "GeeksForGeeks Geeks for For Geeks Geek";          // Creating a matcher for the input String         Matcher matcher             = pattern.matcher(stringToBeMatched);          // Displaying the string to be matched         // before replacing         System.out.println("Before Replacement: "                            + stringToBeMatched);          // Getting the string to be replaced         String stringToBeReplaced = "GFG";         StringBuilder builder = new StringBuilder();          // Replacing every matched pattern with the target         // string using replaceFirst() method         System.out.println(             "After Replacement: "             + matcher.replaceFirst(stringToBeReplaced));     } } 

Output: 
Before Replacement: GeeksForGeeks Geeks for For Geeks Geek After Replacement: GFGForGeeks Geeks for For Geeks Geek

 

Example 2:

Java
// Java Program to Illustrate replaceFirst() Method  // Importing required classes import java.util.regex.*;  // Main class public class GFG {      // Main driver method     public static void main(String[] args)     {          // Getting the regex to be checked         String regex = "(FGF)";          // Creating a pattern from regex         Pattern pattern = Pattern.compile(regex);          // Getting the string to be matched         String stringToBeMatched = "FGF FGF FGF FGF";          // Creating a matcher for the input String         Matcher matcher             = pattern.matcher(stringToBeMatched);          // Printing string on console         // before replacement         System.out.println("Before Replacement: "                            + stringToBeMatched);          // Getting the string to be replaced         String stringToBeReplaced = "GFG";         StringBuilder builder = new StringBuilder();          // Replacing every matched pattern with target         // string using replaceFirst() method and printing         // the string to be replaced         System.out.println(             "After Replacement: "             + matcher.replaceFirst(stringToBeReplaced));     } } 

Output: 
Before Replacement: FGF FGF FGF FGF After Replacement: GFG FGF FGF FGF

 

Next Article
Matcher toString() method in Java with Examples

K

Kirti_Mangal
Improve
Article Tags :
  • Java
  • Java - util package
  • Java-Functions
  • Java-Matcher
Practice Tags :
  • Java

Similar Reads

  • Matcher replaceAll(String) method in Java with Examples
    The replaceAll(String) method of Matcher Class behaves as a append-and-replace method. This method reads the input string and replace it with the matched pattern in the matcher string. Syntax: public String replaceAll(String stringToBeReplaced) Parameters: This method takes a parameter stringToBeRep
    2 min read
  • Matcher quoteReplacement(String) method in Java with Examples
    The quoteReplacement(String string) method of Matcher Class is used to get the replacement String literal of the String passed as parameter. This String literal acts as the parameter for the replace methods. Hence quoteReplacement() method acts as the intermediate in the replace methods. Syntax: pub
    2 min read
  • Matcher start(String) method in Java with Examples
    The start(String string) method of Matcher Class is used to get the start index of the match result already done, from the specified string. Syntax: public int start(String string) Parameters: This method takes a parameter string which is the String from which the start index of the matched pattern
    2 min read
  • String replace() method in Java with Examples
    The String replace() method returns a new string after replacing all the old characters/CharSequence with a given character/CharSequence. Example:Return a new string where all " o" characters are replaced with "p" character: [GFGTABS] Java // Java program to demonstrate // the replace() method publi
    4 min read
  • Matcher toString() method in Java with Examples
    The toString() method of Matcher Class is used to get the String representation of this matcher. This method is derived from the Object Class and behaves in the similar way. Syntax: public String toString() Parameters: This method takes no parameters. Return Value: This method returns a String value
    2 min read
  • Matcher replaceFirst(Function) method in Java with Examples
    The replaceFirst(Function) method of Matcher Class behaves as a append-and-replace method. This method replaces first instance of the pattern matched in the matcher with the function passed in the parameter. Syntax: public String replaceFirst( Function replacerFunction) Parameters: This method takes
    2 min read
  • String matches() Method in Java with Examples
    In Java, the matches() method in the String class checks if a string matches a specified regular expression. It is useful for validating input patterns and searching within strings. In this article, we will learn how to use the matches() method effectively in Java with examples to illustrate its fun
    3 min read
  • Matcher reset() Method in Java with Examples
    The reset() method of Matcher Class is used to reset this matcher, in order to understand it better it is recommended to have prior knowledge of Pattern and Matcher class in java regex sub-package. Here we will be illustrating it with help of Java programs. Syntax: public Matcher reset() Parameters:
    2 min read
  • Matcher usePattern(Pattern) method in Java with Examples
    The usePattern() method of Matcher Class is used to get the pattern to be matched by this matcher. Syntax: public Matcher usePattern(Pattern newPattern) Parameters: This method takes a parameter newPattern which is the new pattern to be set. Return Value: This method returns a Matcher with the new P
    2 min read
  • Matcher regionStart() method in Java with Examples
    The regionStart() method of Matcher Class is used to get the startIndex of the region to be matched by the pattern in the current matcher. This method returns an integer value which is the startIndex of the region of this matcher. Syntax: public int regionStart() Parameters: This method takes no par
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences