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));
    }
}
相关推荐
李少兄6 小时前
Java 工程化基石:标准目录结构与 META-INF 元信息机制
java·开发语言
就叫_这个吧6 小时前
理解Java反射机制和内省机制应用与实践
java·开发语言·反射
未若君雅裁6 小时前
synchronized 底层原理:Monitor、对象头、Mark Word 与锁升级
java
m0_752035636 小时前
markdown语言格式
java
布朗克1686 小时前
12 封装与构造方法
java·开发语言·封装·构造方法
z落落6 小时前
C# 抽象类(abstract)
java·开发语言·c#
大湿兄啊啊啊7 小时前
MID360S调试
java·服务器·前端
.Cnn7 小时前
Maven进阶知识点
java·maven
布朗克1687 小时前
11 面向对象思想入门
java·对象