java字符串转Integer方法(正则表达式)

主打一个拿来就能用

包名:

java 复制代码
import java.util.regex.Matcher;
import java.util.regex.Pattern;

方法:

java 复制代码
// str -> Integer
    public Integer paraseStrToInteger(String str) {
        Pattern pattern = Pattern.compile("\\d+"); // 规则
        Matcher matcher = pattern.matcher(str); // 打工人

        if (matcher.find()) { // 打工人 : 找到了
            return Integer.valueOf(matcher.group()); // 打工人拿到 "数字"(字符串) 转 Integer
        } else {
            return null; // 没找到数字
        }
    }

测试:

java 复制代码
package com.ruoyi.tianyancha.service;

import com.ruoyi.tianyancha.service.impl.AnnualReportServiceImpl;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

@SpringBootTest
public class TestMethod {

    @Autowired
    private AnnualReportServiceImpl annualReportServiceImpl;

    //正则表达式(最通用)
    // "12345人" 转 12345
    @Test
    public void parseStrToInteger(){
        String str = "12345人";

        // 匹配数字部分(支持小数、负数)
        Pattern pattern = Pattern.compile("\\d+");
        Matcher matcher = pattern.matcher(str);

        if (matcher.find()) { // 工人 : 找到了
            System.out.println(matcher.group()); // 拿到:"6792"
            System.out.println(Integer.parseInt(matcher.group())); // 转 int
            System.out.println(Integer.valueOf(matcher.group())); // 转 Integer
//            return Integer.parseInt(matcher.group());
        } else {
            return ;
//            return null; // 没找到数字
        }
    }

    @Test
    public void TestStrToInteger() {
        String str = "12345人";
        System.out.println(annualReportServiceImpl.paraseStrToInteger(str));
    }
}
相关推荐
白鲸开源7 小时前
Apache SeaTunnel Zeta Engine 的 Basic Auth 是怎么工作的?
java·vue.js·github
白鲸开源7 小时前
一文读懂DolphinScheduler插件机制:如何轻松扩展任务类型与数据源
java·架构·github
用户2986985301412 小时前
Java 实现 Word 文档文本查找与高亮标注
java·后端
宇宙之一粟13 小时前
乐企版式文件生成平台
java·后端·python
plainGeekDev13 小时前
MVC 写法 → MVVM
android·java·kotlin
SL_staff13 小时前
3周搭完MES系统:JVS低代码+JVS-IoT物联网的实战记录
java·前端·低代码
MacroZheng13 小时前
斩获20w star!Claude Code最强插件,AI编程必备!
java·人工智能·后端
唐青枫15 小时前
Java Spring WebFlux 实战指南:用 Mono、Flux 和 WebClient 写响应式接口
java·spring
小bo波1 天前
使用Thread子类创建线程 VS 使用Runnable接口创建线程的区别
java·多线程·thread·并发编程·runnable
SamDeepThinking1 天前
高并发场景下,CompletableFuture与ForkJoinPool该如何取舍?
java·后端·面试