从给定字符串|集合2中提取最大数值(正则表达式方法)

给定一个字母数字字符串,从该字符串中提取最大数值。

null

例如:

Input : 100klh564abc365bg
Output : 564
Maximum numeric value among 100, 564 
and 365 is 564.
Input : abchsd0365sdhs
Output : 365

在里面 第一组 ,我们讨论了从给定字符串中提取数值的一般方法。在本文中,我们将讨论 正则表达式 方法相同。

下面是至少一个数字的正则表达式之一。

d+

所以正则表达式的解决方案很简单:

  1. 初始化最大值=0
  2. 在matcher上运行循环,只要找到匹配项,就将数字字符串转换为整数,并将其与MAX进行比较。
    • 如果数字大于最大值,请将最大值更新为数字。
  3. 最后把麦克斯还给我。

// Java regex program to extract the maximum value
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class GFG
{
// Method to extract the maximum value
static int extractMaximum(String str)
{
// regular expression for atleast one numeric digit
String regex = "\d+" ;
// compiling regex
Pattern p = Pattern.compile(regex);
// Matcher object
Matcher m = p.matcher(str);
// initialize MAX = 0
int MAX = 0 ;
// loop over matcher
while (m.find())
{
// convert numeric string to integer
int num = Integer.parseInt(m.group());
// compare num with MAX, update MAX if num > MAX
if (num > MAX)
MAX = num;
}
return MAX;
}
public static void main (String[] args)
{
String str = "100klh564abc365bg" ;
System.out.println(extractMaximum(str));
}
}


输出:

564

但若数字大于整数范围,上述程序将无法运行。你可以试试 parseLong() 最高达 长的 范围但要处理大量(大于 长的 范围)我们可以帮助 大整数 用java编写的类。下面是一个java程序来演示这一点。

// Java regex program to extract the maximum value
// in case of large numbers
import java.math.BigInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class GFG
{
// Method to extract the maximum value
static BigInteger extractMaximum(String str)
{
// regular expression for atleast one numeric digit
String regex = "\d+" ;
// compiling regex
Pattern p = Pattern.compile(regex);
// Matcher object
Matcher m = p.matcher(str);
// initialize MAX = 0
BigInteger MAX = BigInteger.ZERO;
// loop over matcher
while (m.find())
{
// convert numeric string to BigIntegr
BigInteger num = new BigInteger(m.group());
// compare num with MAX, update MAX if num > MAX
if (num.compareTo(MAX) > 0 )
MAX = num;
}
return MAX;
}
public static void main (String[] args)
{
String str = "100klh564231315151313151315abc365bg" ;
System.out.println(extractMaximum(str));
}
}


输出:

564231315151313151315

本文由 高拉夫·米格拉尼 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 贡献极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。

如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞5 分享