如何使用正则表达式从字符串中提取数字?
您可以使用以下任一正则表达式匹配给定字符串中的数字-
“\\d+” Or, "([0-9]+)"
例子1
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ExtractingDigits {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter sample text: ");
String data = sc.nextLine();
//正则表达式以匹配字符串中的数字
String regex = "\\d+";
//创建一个模式对象
Pattern pattern = Pattern.compile(regex);
//创建一个Matcher对象
Matcher matcher = pattern.matcher(data);
System.out.println("Digits in the given string are: ");
while(matcher.find()) {
System.out.print(matcher.group()+" ");
}
}
}输出结果
Enter sample text: this is a sample 23 text 46 with 11223 numbers in it Digits in the given string are: 23 46 11223
例子2
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Just {
public static void main(String[] args) {
String data = "abc12def334hjdsk7438dbds3y388";
//正则表达式到数字
String regex = "([0-9]+)";
//创建一个模式对象
Pattern pattern = Pattern.compile(regex);
//创建一个Matcher对象
Matcher matcher = pattern.matcher(data);
System.out.println("Digits in the given string are: ");
while(matcher.find()) {
System.out.print(matcher.group()+" ");
}
}
}输出结果
Digits in the given string are: 12 334 7438 3 388
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短