在 Java 中,可以使用 正则表达式(Regex) 配合 Pattern 和 Matcher 来提取字符串中的数字。下面按常见场景给你示例。
import java.util.regex.*;
import java.util.*;
public class Test {
public static void main(String[] args) {
String text = "订单123和456,总价7890元";
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(text);
List<String> numbers = new ArrayList<>();
while (matcher.find()) {
numbers.add(matcher.group());
}
System.out.println(numbers); // [123, 456, 7890]
}
}
Pattern pattern = Pattern.compile("\\d+\\.\\d+");
示例:
String text = "价格是12.34和56.78元";
Pattern pattern = Pattern.compile("\\d+\\.\\d+");
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
System.out.println(matcher.group());
}
Pattern pattern = Pattern.compile("\\d+(\\.\\d+)?");
String text = "数值是 123 和 45.6";
Pattern pattern = Pattern.compile("\\d+(\\.\\d+)?");
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
String numStr = matcher.group();
if (numStr.contains(".")) {
System.out.println(Double.parseDouble(numStr));
} else {
System.out.println(Integer.parseInt(numStr));
}
}
Pattern pattern = Pattern.compile("-?\\d+(\\.\\d+)?");
String text = "abc123def";
Matcher matcher = Pattern.compile("\\d+").matcher(text);
if (matcher.find()) {
System.out.println(matcher.group()); // 123
}
| 正则 | 含义 |
|---|---|
\\d |
数字 |
\\d+ |
一个或多个数字 |
\\. |
小数点 |
-? |
可选的负号 |
() |
分组 |
如果你是 从 JSON / 日志 / HTML / 特定格式 中提取数字,可以告诉我具体场景,我可以给你更精准的正则。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。