主打一个拿来就能用
包名:
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));
}
}
