编程人 cdmana.com

Getting started with Java lesson 88 -- string substitution using replaceall

problem

     Use replaceAll Implement string substitution , The specific requirement is to string "abc123bcd45ef6g7890" Replace the numbers in with Chinese characters " Numbers ", If it's a continuous number , Then replace it with a Chinese character " Numbers ".

programme

     stay Java API Medium String Provides replaceAll Method , Implementation of string matching regular expression string replaced by other strings ,replaceAll The method is declared as follows :

String replaceAll(String regex,String replacement)

     The above method can match regular expression in string regex Replace the string of with replacement.

step

     To implement this case, follow the steps below .

Step one : Add test method

     stay TestRegEx Add test method to testReplaceAll, The code is as follows :

    package day02;
    
    import org.junit.Test;
    import java.util.Arrays;
    
    public class TestRegEx{
    
    /**
     * Use replaceAll Method to implement string substitution 
     *
     */
     @Test
     public void testReplaceAll(){
     
     }     
    }

Step two : Use replaceAll Method

     The string "abc123bcd45ef6g7890" Replace the numbers in with Chinese characters " Numbers ", If it's a continuous number , Then replace it with a Chinese character " Numbers ", In regular expressions , Use "[\\d+]" To indicate that one or more numbers can appear , The code is as follows :

    package day02;
    
    import org.junit.Test;
    import java.util.Arrays;
    
    public class TestRegEx{
    
    /**
     * Use replaceAll Method to implement string substitution 
     *
     */
     @Test
     public void testReplaceAll(){
     
         // take str Replace all numbers in with " Numbers " Two words 
         String str="abc123bcd45ef6g7890";
         str=str.replaceAll("\\d+"," Numbers ");
         System.out.println(str);
     }     
    }

Step three : function

     Operation method testReplaceAll, The console output is as follows :

abc Numbers bcd Numbers ef Numbers g Numbers 

     From the output, you can see that the string "abc123bcd45ef6g7890" Replace the numbers in with Chinese characters " Numbers ".

Official account , Get a learning video

Scroll to Top