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

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

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

问题

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

  1. "$z4~min.~00~s" -> 4
  2. "$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:

  1. "$z4~min.~00~s" -> 4
  2. "$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

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

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:

确定