假设以下是我们的包含整数和字符的字符串-
String str = "(29, 12; 29, ) (45, 67; 78, 80)";
现在,要提取整数,我们将使用以下模式-
\d
我们已经用Pattern类设置了它-
Matcher matcher = Pattern.compile("\\d+").matcher(str);
import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Demo { public static void main(String[] args) { String str = "(29, 12; 29, ) (45, 67; 78, 80)"; Matcher matcher = Pattern.compile("\\d+").matcher(str); List<Integer>list = new ArrayList<Integer>(); while(matcher.find()) { list.add(Integer.parseInt(matcher.group())); } System.out.println("Integers = "+list); } }
输出结果
Integers = [29, 12, 29, 45, 67, 78, 80]