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));
    }
}
相关推荐
0xDevNull4 小时前
Java反射机制深度解析:从原理到实战
java·开发语言·后端
华科易迅4 小时前
MybatisPlus增删改查操作
android·java·数据库
standovon4 小时前
Spring Boot整合Redisson的两种方式
java·spring boot·后端
Amumu121384 小时前
Js:正则表达式(二)
开发语言·javascript·正则表达式
IAUTOMOBILE5 小时前
Python 流程控制与函数定义:从调试现场到工程实践
java·前端·python
hutengyi5 小时前
PostgreSQL版本选择
java
皮皮林5515 小时前
重磅!JetBrains 正式发布全新的 AI 开发工具,定名 AI IDE AIR
java·intellij idea
MX_93595 小时前
SpringMVC请求参数
java·后端·spring·servlet·apache
ID_180079054735 小时前
小红书笔记评论 API,Python 调用示例与完整 JSON 返回参考
java·开发语言
lifewange5 小时前
java连接Mysql数据库
java·数据库·mysql