java中如何截取字符串中的一串数字
时间: 2024-04-13 11:29:56 浏览: 34
在 Java 中,你可以使用正则表达式或者遍历字符来截取字符串中的一串数字。
方法1:使用正则表达式
你可以使用正则表达式来匹配字符串中的数字部分,并提取出来。下面的示例演示了如何使用正则表达式来截取字符串中的数字:
```java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String str = "abc123def456";
String regex = "\\d+"; // 匹配一个或多个数字
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
String number = matcher.group();
System.out.println(number);
}
}
}
```
输出:
```
123
456
```
方法2:遍历字符
另一种方法是遍历字符串的每个字符,判断是否为数字字符,然后将连续的数字字符连接起来。下面的示例演示了如何使用遍历字符的方法来截取字符串中的一串数字:
```java
public class Main {
public static void main(String[] args) {
String str = "abc123def456";
StringBuilder number = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (Character.isDigit(ch)) {
number.append(ch);
} else if (number.length() > 0) {
System.out.println(number);
number.setLength(0); // 清空StringBuilder,准备下一个数字
}
}
if (number.length() > 0) {
System.out.println(number);
}
}
}
```
输出:
```
123
456
```
无论使用正则表达式还是遍历字符的方法,都可以截取字符串中的一串数字。你可以根据具体的需求选择合适的方法来处理字符串。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)