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);
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP