正则表达式 – 查找出现在特定字符前的所有数字

huangapple go评论88阅读模式
英文:

Regex - Find all the digits that occur to a certain character

问题

关于正则表达式,我想问你一下 - 我需要获取所有出现在特定字符之前的数字。例如:

"$z4~min.~00~s" -> 4
"$z12~min.~00~s" -> 12

我只需要字符串中的第一个数字,不需要字符串中小数点后面的数字。

我在这个项目中使用Java。

你有什么建议吗?非常感谢。

英文:

I would like to ask you about regex expression - I need to get all numbers that occur to a certain character. For example:

"$z4~min.~00~s" -> 4
"$z12~min.~00~s" -> 12

I simply need first number in the string, I don't need numbers after dot in the string.

I am using Java for this project.

Do you have any suggestions? Thanks a lot.

答案1

得分: 0

import java.util.regex.Pattern;
import java.util.regex.Matcher;

Pattern pattern = Pattern.compile("^\\D*(\\d+)");
Matcher matcher = pattern.matcher("$z12~min.~00~s");
if (matcher.find()) {
    String firstNumber = matcher.group(1);
    System.out.println(firstNumber);
}
英文:
java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("^\\D*(\\d+)");
java.util.regex.Matcher matcher = pattern.matcher("$z12~min.~00~s");
if (matcher.find()) {
    String firstNumber = matcher.group(1);
    System.out.println(firstNumber);
}

huangapple
  • 本文由 发表于 2020年8月19日 01:03:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/63473374.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定