查找字符串中的数字
import org.apache.commons.lang3.StringUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author created on 2021/5/26
*/
public class Test {
public static void main(String[] args) {
test1();
System.out.println("----------");
test2();
}
private static void test1() {
String str = "(1or12)and23or29";
List<String> numberList = new ArrayList();
String str2 = "";
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) >= 48 && str.charAt(i) <= 57) {
str2 += str.charAt(i);
} else {
if (StringUtils.isNotBlank(str2)) {
numberList.add(str2);
str2 = "";
}
}
if (i == str.length() - 1 && StringUtils.isNotBlank(str2)) {
numberList.add(str2);
}
}
numberList.forEach(System.out::println);
}
private static void test2() {
String str = "(1or12)and23or29";
String regEx = "[^0-9]";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(str);
//将非数字的部分替换为\t
String trim = m.replaceAll("\t").trim();
//使用\t分隔
String[] split = trim.split("\t");
for (String s : split) {
//所有非空的为数字
if (StringUtils.isNotBlank(s)) {
System.out.println(s);
}
}
}
}
从 https://www.cnblogs.com/android-html5/archive/2012/06/02/2533926.html 优化而来。