我有String with FirstName + "/" + LastName +" "+ DateOfBirthday
FirstName
和LastName
可以包含SPACE(“”)和DASH(“ - ”)DateOfBirthday
只能格式为([0-9]{2}+[A-Za-z]+[0-9]{2})
,而且可以在字符串之前或之后。 请帮助我删除DASH
和SPACE
FirstName
和LastName
示例:
- Hanry Klark/Jacobson 23FEB16 - HanryKlark/Jacobson 23FEB16
- Hanry-Klark/Jaco-Bson 23FEB16 - HanryKlark/JacoBson 23FEB16
- Hanry/Jaco 23FEB16 - Hanry/Jaco 23FEB16
- 23FEB16 Hanry-Klark/Jaco Bson - 23FEB16 HanryKlark/JacoBson
我试过了......
String additionalInfo = "23FEB16 Hanry-Klark/Jaco Bson";
String datePattren = "[0-9]{1,}+[A-Za-z]+[0-9]{1,}";
Pattern pattern = Pattern.compile(datePattren);
Matcher matcher = pattern.matcher(additionalInfo);
matcher.find();
String Date = matcher.group();
additionalInfo = additionalInfo.replaceAll(datePattren, "").replaceAll(" ", "").replaceAll("-","");
if (Date!=""){
additionalInfo = additionalInfo + " " + Date;
}
Meybe有一个更美丽的解决方案吗?
答案 0 :(得分:1)
您可以将([a-zA-Z]+)(?:\\s|-)([a-zA-Z]+)
与replaceAll
([a-zA-Z]+)
:捕获一个或多个字母,由$1
(?:\\s|-)
:非捕获组以匹配空格或-
字符
([a-zA-Z]+)
:捕获一个或多个字母,由$2
所以请使用:additionalInfo.replaceAll("([a-zA-Z]+)(?:\\s|-)([a-zA-Z]+)", "$1$2")
演示
const aar =['Hanry Klark/Jacobson 23FEB16','Hanry-Klark/Jaco-Bson 23FEB16',
'Hanry/Jaco 23FEB16','23FEB16 Hanry-Klark/Jaco Bson']
const regex =/([a-zA-Z]+)(?:\s|-)([a-zA-Z]+)/g;
for(var i in aar)
console.log(aar[i].replace(regex,'$1$2'));