主要可用于将字符串内年月数据的提取
已测试字符串类型如下
String a = “2019年11月”;
// String a = “2019年1月”;
// String a=“2019/1”;
// String a=“2019-1”;
// String a=“20191”;
// String a=“201901”;
// String a=“2019.1”;
// String a=“2019.012”; // 异常
String a = “2019.02”;
public static void main(String[] args) {
// String a = "2019年11月";
// String a = "2019年1月";
// String a="2019/1";
// String a="2019-1";
// String a="20191";
// String a="201901";
// String a="2019.1";
// String a="2019.012"; // 异常
String a = "2019.02";
YM ym = getYM(a);
if (ym != null) {
System.out.println(ym.toString());
} else {
System.out.println("null");
}
}
全部工具代码如下
package com.*;
import com.work.common.utils.StringUtils;
import lombok.Data;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Data
public class YM {
private Integer ym;
private Integer y;
private Integer m;
/**
* @param ym 入参类型
* 1. 2019年1月
* 2. 2019/1
* 3. 2019-1
* 4. 20191
* 5. 201901
* 6. 2019.1
* @return
*/
public static YM getYM(String ym) {
YM back = new YM();
if (StringUtils.isBlank(ym)) {
return null;
}
if (ym.length() < 5) {
return null;
}
String yString = null;
String mString = null;
try {
Integer ymInteger = Integer.valueOf(ym);
yString = ym.substring(0, 4);
mString = ym.substring(4);
} catch (Exception e) {
String regEx = "[0-9]+";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(ym);
if (m.find()) {
yString = m.group(0);
}
if (m.find()) {
mString = m.group(0);
}
}
if (StringUtils.isBlank(yString) || StringUtils.isBlank(mString)) {
return null;
}
if (yString.length() != 4 || mString.length() > 2) {
return null;
}
back.setY(Integer.valueOf(yString));
back.setM(Integer.valueOf(mString));
if (mString.length() == 1) {
String ymString = yString + "0" + mString;
back.setYm(Integer.valueOf(ymString));
} else {
String ymString = yString + mString;
back.setYm(Integer.valueOf(ymString));
}
return back;
}
}