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));
    }
}
相关推荐
前端技术2 小时前
【鸿蒙实战】从零打造智能物联网家居控制系统:HarmonyOS Next分布式能力的完美诠释
java·前端·人工智能·分布式·物联网·前端框架·harmonyos
05大叔2 小时前
Mybatis-Plus
java·开发语言·mybatis
杜子不疼.2 小时前
Spring Cloud+AI :实现分布式智能推荐系统
java·人工智能·spring cloud
毕设源码-朱学姐2 小时前
【开题答辩全过程】以 基于springBoot微服务架构的老年人社交系统的设计与实现为例,包含答辩的问题和答案
java·spring boot·后端
java1234_小锋2 小时前
Python常见面试题:Python是如何进行内存管理的?
java·jvm·python
Vic101012 小时前
java的分布式协议
java·开发语言·分布式
Mr.朱鹏2 小时前
分布式-redis主从复制架构
java·spring boot·redis·分布式·缓存·架构·java-ee
识君啊2 小时前
Java字符串算法核心攻略
java·数据结构·算法·leetcode·字符串·
程序员夏末2 小时前
【AI Agent基础 | 第四篇】Spring AI 集成与多模型支持
java·人工智能·spring·ai·ai agent