带有空格或短划线的正则表达式名和姓

时间:2017-03-21 14:17:16

标签: java regex space

我有String with FirstName + "/" + LastName +" "+ DateOfBirthday

  1. FirstNameLastName可以包含SPACE(“”)和DASH(“ - ”)
  2. DateOfBirthday只能格式为([0-9]{2}+[A-Za-z]+[0-9]{2}),而且可以在字符串之前或之后。
  3. 请帮助我删除DASHSPACE

    中的FirstNameLastName

    示例:

     - 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有一个更美丽的解决方案吗?

1 个答案:

答案 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'));