Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

Matcher replaceFirst() Method ใน Java พร้อมตัวอย่าง


คลาส java.util.regex.Matcher แทน engine ที่ดำเนินการจับคู่ต่างๆ ไม่มี constructor สำหรับคลาสนี้ คุณสามารถสร้าง/ได้รับ object ของคลาสนี้โดยใช้เมธอด matches() ของคลาส java.util.regex.Pattern

เมธอด replaceFirst() ของคลาส (Matcher) นี้รับค่าสตริง และแทนที่ subsequence ที่จับคู่ได้ครั้งแรกในข้อความอินพุตด้วยค่าสตริงที่กำหนด และคืนค่าผลลัพธ์

ตัวอย่างที่ 1: แทนที่ # ครั้งแรกด้วย @

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ReplaceFirstExample {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter input text: ");
        String input = sc.nextLine();
        String regex = "[#]";
        
        // สร้าง Pattern object
        Pattern pattern = Pattern.compile(regex);
        
        // สร้าง Matcher object
        Matcher matcher = pattern.matcher(input);
        int count = 0;
        while (matcher.find()) {
            count++;
        }
        
        // ดึง Pattern ที่ใช้
        System.out.println("The are character # occurred " + count + " times in the given text");
        
        // แทนที่ครั้งแรกด้วย @
        String result = matcher.replaceFirst("@");
        System.out.println("Text after replacing the first occurrence of # with @ \n" + result);
    }
}

Output

Enter input text: Enter input text: Hello# How # are# you #welcome to Tutorials#point
The are character # occurred 5 times in the given text
Text after replacing the first occurrence of # with @ Hello@ How # are# you #welcome to Tutorials#point

ตัวอย่างที่ 2: แทนที่ช่องว่างครั้งแรกด้วย _

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ReplaceFirstExample {
    public static void main(String args[]) {
        // อ่าน String จากผู้ใช้
        System.out.println("Enter a String");
        Scanner sc = new Scanner(System.in);
        String input = sc.nextLine();
        String regex = "\\s+";
        
        // คอมไพล์ regular expression
        Pattern pattern = Pattern.compile(regex);
        
        // ดึง Matcher object
        Matcher matcher = pattern.matcher(input);
        
        // แทนที่ช่องว่างครั้งแรกด้วย _
        String result = matcher.replaceFirst("_");
        System.out.print("Text after replacing the first space with '_': \n" + result);
    }
}

Output

Enter a String hello this is a sample text with irregular spaces
Text after replacing the first space with '_': hello_this is a sample text with irregular spaces