正則表達式$1,$2是什么意思


$1,$2表達的是小括號分組里面的內容:$1是第一個小括號里的內容,$2是第二個小括號里面的內容,依此類推。例如:

str = str.replaceAll("(\\d+)","\\*$1\\*");
// s1就表示正則表達式第一個括號內匹配到的內容。
// 如:  123      *123*

使用41相關正則可以減少代碼量,如以下機試題:

描述

將一個字符中所有的整數前后加上符號“*”,其他字符保持不變。連續的數字視為一個整數。

注意:本題有多組樣例輸入。
import java.util.Scanner;
import java.util.regex.Pattern;
// 不使用$1 public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        while(sc.hasNextLine()) {
            String str = sc.nextLine();
            StringBuffer sb = new StringBuffer();
            if(str.matches("[0-9]{1,}")) {
                System.out.println("*" + str + "*");
            } else {
                String temp;
                for (int i = 0; i < str.length(); i++) {
                    temp = String.valueOf(str.charAt(i));
                    if(temp.matches("[0-9]")) {
                        if(i == 0 || String.valueOf(str.charAt(i-1)).matches("[^0-9]")) {
                            sb.append("*");
                        }
                        sb.append(temp);
                        if(i == str.length() - 1 || String.valueOf(str.charAt(i+1)).matches("[^0-9]")) {
                            sb.append("*");
                        }
                    } else {
                        sb.append(temp);
                    }
                }
                System.out.println(sb);
            }
        }
    }
}
import java.util.*;
// 使用$1 public class Main{
  public static void main(String[] args){
    Scanner sc = new Scanner(System.in);
    while(sc.hasNext()){
      String str = sc.nextLine();
      str = str.replaceAll("(\\d+)","\\*$1\\*");
      System.out.println(str);
    }
  }
}

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM