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));
    }
}
相关推荐
BLUcoding1 分钟前
接口服务公网超时排查记录:SecureRandom 阻塞问题分析与解决
java·linux·springboot·aes·securerandom
yuniko-n17 分钟前
【JUC】Lock 和 synchronzied 锁
java
西柚小萌新23 分钟前
【LLM&&AI应用开发 八股文】--4.3.Agent智能体(下)
java·开发语言·数据库
北极有牛26 分钟前
cpp学习笔记--常量指针
java·开发语言·算法
java资料站33 分钟前
二、Spring AI Alibaba · ChatModel
java·windows·spring
十年Java程序媛1 小时前
Java 接口和抽象类对比|Java8 新特性,抛弃老旧八股,正确选型
java·spring boot·后端
caoerzhong1 小时前
JeeWMS 开源 WMS 部署避坑指南:Java 仓库管理系统的环境基线、四类根因与可复现交付
java·开发语言·开源
用户3721574261351 小时前
Java 合并 PDF 文件:完整合并、指定页面合并与流合并
java
for_ever_love__2 小时前
MySQL 全文索引实战:FULLTEXT、ngram 中文分词与 MATCH AGAINST 到底该怎么用
java·python·mysql·全文检索·分词·索引·ngram
java资料站2 小时前
五、Spring AI Alibaba · Memory · Saver(短期会话)
java·spring·microsoft