Java Regex从字符串中提取最大数值
最大值是从字母数字字符串中提取的。一个例子如下:
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);热门推荐
1 带狗狗训练
4 听力训练狗狗
6 怎训练狗狗
7 腹肌训练狗狗
8 网球训练狗狗
9 记叙文训练狗狗
10 狗狗太凶怎么训练
11 核心力量训练狗狗
12 狗狗乱叫怎么训练
13 发音训练狗狗
14 怎么训练狗狗叼东西给主人
15 荆州训练狗狗
16 篮球训练狗狗
17 做训练狗狗
18 训练狗狗坐姿