117.info
人生若只如初见

java怎么提取字符串中的数字

要提取字符串中的数字,可以使用正则表达式或循环遍历字符串的方法。

方法一:使用正则表达式

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) {
        String str = "abc123def456ghi789";
        Pattern pattern = Pattern.compile("\\d+"); // 匹配一个或多个数字
        Matcher matcher = pattern.matcher(str);
        while (matcher.find()) {
            System.out.println(matcher.group()); // 打印匹配到的数字
        }
    }
}

方法二:使用循环遍历字符串

public class Main {
    public static void main(String[] args) {
        String str = "abc123def456ghi789";
        StringBuilder number = new StringBuilder();
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (Character.isDigit(c)) {
                number.append(c); // 如果是数字,追加到StringBuilder中
            } else if (number.length() > 0) {
                System.out.println(number.toString()); // 打印数字
                number.setLength(0); // 清空StringBuilder
            }
        }
        if (number.length() > 0) {
            System.out.println(number.toString()); // 打印最后一个数字
        }
    }
}

以上两种方法都可以提取字符串中的数字,使用哪种方法取决于具体的需求和个人喜好。

未经允许不得转载 » 本文链接:https://www.117.info/ask/fe1d5AzsLBQBSBVM.html

推荐文章

  • java中怎么判断csv文件是否存在

    在Java中,可以使用java.io.File类的exists()方法来判断文件是否存在。
    import java.io.File;
    public class Main {
    public static void main(Str...

  • java怎么读取property文件

    在Java中,可以使用java.util.Properties类来读取property文件。
    以下是读取property文件的步骤: 创建Properties对象: Properties properties = new Prop...

  • java中resultset怎么使用

    在Java中,ResultSet是一个接口,用于获取和处理数据库查询的结果。以下是一些使用ResultSet的常见步骤: 创建一个Statement对象,并使用该对象执行查询语句。例...

  • 怎么用java calendar获取年月日

    要使用Java Calendar类获取年月日,可以按照以下步骤进行操作: 首先,导入java.util.Calendar类: import java.util.Calendar; 创建一个Calendar对象: Calenda...

  • golang怎么防止反编译

    在Go语言中,可以采取一些措施来防止反编译,以下是一些常见的方法: 使用代码混淆:通过对代码进行混淆,使得反编译后的代码难以理解。可以使用工具如ProGuard来...

  • golang字符串处理的方法有哪些

    在Go语言中,有许多内置的字符串处理方法和函数。以下是一些常用的方法: len(str):返回字符串的长度。
    str[index]:返回字符串中指定索引位置的字符。

  • MySQL无响应没有报错怎么解决

    MySQL无响应但没有报错的情况,可能是由于以下几个原因引起的: MySQL服务器负载过高:如果服务器负载过高,可能会导致MySQL无法响应请求。可以通过查看服务器的...

  • 怎么用java判断日期格式是否正确

    你可以使用SimpleDateFormat类来判断日期格式是否正确。以下是一个示例:
    import java.text.ParseException;
    import java.text.SimpleDateFormat; pub...