需要正则代码以在邮政编码的末尾删除仪表板,除非仪表板之后有数字



我的zipcodes是5位数字,我的zipcodes是9位数字,介于两者之间。

问题是5位邮政编码的末端具有破折号,我只想在邮政编码不是9位Zipcodes时删除破折号。

其他澄清:因此,我的Zipcodes采用以下格式:##### - 和##### - ####。我想将其更改为#####和##### - ####

if(zipCode.endsWith("-")) {  
    // remove '-' 
}
if (postcode.length() == 6)
        postcode = postcode.substring(0,5);

您可以使用此正则:

(?<=^[0-9]{5})(-)(?=$)

工作正则示例:

http://regex101.com/r/oo1hg2

Java代码:

str = str.replaceAll("(?<=^[0-9]{5})(-)(?=$)", "");
Pattern p1 = Pattern.compile("(\d{5})-?");
Pattern p2 = Pattern.compile("(\d{4})-?(\d{5})");
Matcher matcher = p1.matcher(zipCode);
String parsed;
if (matcher.find()) {
   parsed = matcher.group(1);
} else {
   matcher = p2.matcher(zipCode);
   if (matcher.find()) {
      parsed = matcher.group(1) + matcher.group(2);
   }
}

我要做的是:

if(zipcode.matches("\d{5}-") //if zipcode is five digits (d{5}) followed by a hyphen (-)...
{
    zipcode = zipcode.substring(0, zipcode.length() - 1); //...make zipcode equal itself minus the last character
}
^([0-9]{5})-$

作为例如(正则示例),09090-的匹配将为:

0: [0,6] 09090-
1: [0,5] 09090

您可以将其替换为匹配

/^([0-9]{5})[-][0-9]{4}$/   //skip replacement.

最新更新