gpt4 book ai didi

Java,正则表达式匹配字符串中的前 10 位数字,忽略前导零

转载 作者:行者123 更新时间:2023-12-02 06:01:52 26 4
gpt4 key购买 nike

我有兴趣从长字符串中提取前 10 位数字(如果存在),同时忽略前导零。另外,如果只有零,则仅返回 1 个零,如果没有数字,则返回空字符串。我希望在一次查找中匹配它。

例如:

  • "abcd00111.g2012asd" 应匹配 "1112012"
  • “aktr0011122222222222ddd” 应与 “1112222222”
  • 匹配
  • "asdas000000asdasds0000" 应与 "0"
  • 匹配
  • "adsads.cxzv.;asdasd" 应与 ""
  • 匹配

这是我迄今为止尝试过的:Ideone Demo - code

Pattern p = Pattern.compile("[1-9]{1}+[0-9]{9}");
Matcher m = p.matcher(str);
if (m.find()) {
String match = m.group();
System.out.println(match);
}

问题是这个正则表达式需要第一个非零之后的 9 个连续数字,而我需要任何 9 个数字(中间可能有非数字字符)。

请注意,在代码中我有 if (m.find()) 而不是 while (m.find()) 因为我希望在中找到匹配项单次运行。

更新

根据评论,我了解到正则表达式不可能在单次运行中完成此操作。

我想要一个不必基于正则表达式但最有效的答案,因为我会多次执行此方法。

最佳答案

一般情况下,不可能通过单个 find 来完成此操作。如果您知道连续数字序列的最大数量,则可以做到这一点,但如果不知道,则这是不可能的,至少在 Java Pattern 类的支持级别上是不可能的。 我错了。 Kobi's comment表明使用单个正则表达式是可能的。我将在这里重现评论:

Oh, and it is sort of possible with a regex, by capturing each of the 10 digits, something like: ^[\D0]*(\d)\D*(?:(\d)\D*(?:(\d)\D*(?:(\d)\D*(?#{6 more times}))?)?)?, but it is really ugly, and doesn't scale well.

不过,您仍然需要连接这些组。正则表达式开头的逻辑非常好:由于贪婪属性,它将搜索所有前导零(如果有)之后的第一个非零数字,或者如果没有非零数字,则将取最后一个0 -零数字。

<小时/>

如果您不谈效率,并且想要简短的代码:

String digitOnly = str.replaceAll("\\D+", "");
String noLeadingZero = digitOnly.replaceFirst("^0+", "");
String result = digitOnly.isEmpty() ? "" :
noLeadingZero.isEmpty() ? "0" :
noLeadingZero.substring(0, Math.min(noLeadingZero.length(), 10));
<小时/>

坦率地说,使用 StringBuilder 循环遍历字符串就足够了,而且它应该比正则表达式解决方案更快。

StringBuilder output = new StringBuilder();
boolean hasDigit = false;
boolean leadingZero = true;
for (int i = 0; i < str.length() && output.length() < 10; i++) {
char currChar = str.charAt(i);
if ('0' <= currChar && currChar <= '9') {
hasDigit = true;
if (currChar != '0') {
output.append(currChar);
leadingZero = false;
} else if (!leadingZero) { // currChar == 0
output.append(currChar);
} // Ignore leading zero
}
}

String result = !hasDigit ? "" :
output.length() == 0 ? "0" :
output.toString();

Performance testing code 。请注意,您应该调整参数以使其类似于实际输入,以便获得良好的近似值。我怀疑循环方法比任何涉及正则表达式的方法都慢;然而,这种差异仅在大范围内才显着。

关于Java,正则表达式匹配字符串中的前 10 位数字,忽略前导零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15105672/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com