java 正则表达式 获取第一个字母前的数字
假设有一个字符串 "123abc",需要获取其第一个字母前的数字,可以使用 Java 正则表达式来实现。
代码如下:
String str = "123abc";
Pattern pattern = Pattern.compile("^\\d+");
Matcher matcher = pattern.matcher(str);
if (matcher.find()) {
String number = matcher.group();
System.out.println(number);
}
解释:
^表示匹配字符串的开头\\d+表示匹配一或多个数字
通过 Pattern 类的 compile 方法可以将正则表达式编译成一个模式,然后使用 Matcher 类的 matcher 方法将要匹配的字符串作为参数传入,最后使用 find 方法查找匹配的字符串。
如果找到了匹配的字符串,可以使用 group 方法获取匹配的部分。
以上代码输出结果为:
123
原文地址: https://www.cveoy.top/t/topic/0kW 著作权归作者所有。请勿转载和采集!