英文:
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);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论