Java 正則表示式從字串中提取最大數值


最大數值是從字母數字字串中提取的。這裡給出一個示例 −

String = abcd657efgh234
Maximum numeric value = 657

演示此操作的程式如下 −

示例

 即時演示

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
 public static void main (String[] args) {
    String str = "123abc874def235ijk999";
    System.out.println("The string is: " + str);
    String regex = "\d+";
    Pattern ptrn = Pattern.compile(regex);
    Matcher match = ptrn.matcher(str);
    int maxNum = 0;
    while(match.find()) {
       int num = Integer.parseInt(match.group());
       if(num > maxNum) {
          maxNum = num;
       }
    }
    System.out.println("The maximum numeric value in above string is: " + maxNum);
 }
}

輸出

The string is: 123abc874def235ijk999
The maximum numeric value in above string is: 999

現在讓我們瞭解上述程式。

首先,顯示字串。然後,為至少一個數字建立正則表示式。然後編譯正則表示式並建立匹配器物件。演示此操作的程式碼段如下。

String str = "123abc874def235ijk999";
System.out.println("The string is: " + str);
String regex = "\d+";
Pattern ptrn = Pattern.compile(regex);
Matcher match = ptrn.matcher(str);

使用 while 迴圈來查詢字串中的最大數值。然後顯示 maxNum。演示此操作的程式碼段如下 −

int maxNum = 0;
while(match.find()) {
 int num = Integer.parseInt(match.group());
 if(num > maxNum) {
    maxNum = num;
 }
}
System.out.println("The maximum numeric value in above string is: " + maxNum);

更新於: 2020 年 6 月 26 日

522 次瀏覽

開啟你的職業生涯

完成課程並獲取認證

開始
廣告
© . All rights reserved.