Java - 邮政编码验证器不工作?

Java - Zip Code Validator not working?

我的邮政编码验证器有一些问题,它读取带有英国邮政编码的文本文件,然后在验证后 returns true 或 false。

下面是我特别遇到问题的代码部分 (ZipCodeValidator),它是 public,应该在名为 ZipCodeValidator.java 的文件中声明。然后 (Zip) 找不到符号。

public class ZipCodeValidator {
    private static String regex = "^[A-Z]{1,2}[0-9R][0-9A-Z]? [0-9][ABD-HJLNP-UW-Z]{2}$";
    private static Pattern pattern = Pattern.compile(regex);

    public boolean isValid(String zipCode) {
        Matcher matcher = pattern.matcher(zip);
        return matcher.matches();
    }
}

下面是整个程序供参考。感谢任何帮助。

package postcodesort;

import java.util.*;
import java.util.Random;
import java.util.Queue;
import java.util.TreeSet;
import java.io.File;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedList;
import java.util.StringTokenizer;
import java.util.zip.ZipFile;
import java.util.regex.Matcher;
import java.util.regex.Pattern;




public class PostCodeSort 
{
    Queue<String> postcodeStack = new LinkedList<String>();

    public static void main(String[] args) throws IOException 
    {
        FileReader fileReader = null;
        ZipCodeValidator zipCodeValidator = new ZipCodeValidator();

        // Create the FileReader object
        try {
            fileReader = new FileReader("postcodes1.txt");
            BufferedReader br = new BufferedReader(fileReader);

            String str;
            while((str = br.readLine()) != null) 
            {
                if(zipCodeValidator.isValid(str)){
                    System.out.println(str + " is valid");
                }
                else{
                    System.out.println(str + " is not valid");
                }
            }
        }
        catch (IOException ex) 
        {
            // handle exception;
        }

        finally 
        {
            fileReader.close();
        }

    }
}

public class ZipCodeValidator {
    private static String regex = "^[A-Z]{1,2}[0-9R][0-9A-Z]? [0-9][ABD-HJLNP-UW-Z]{2}$";
    private static Pattern pattern = Pattern.compile(regex);

    public boolean isValid(String zipCode) {
        Matcher matcher = pattern.matcher(zip);
        return matcher.matches();
    }
}

可能是复制+粘贴问题,但 Matcher matcher = pattern.matcher(zip); 与方法参数 zipCode 不匹配。您是否在其他地方定义了 zip,并可能对其进行验证?

It's when I added the read file code thats when the problems arose like the ones I specified above

确保在传入之前清理字符串。要删除任何前导或尾随空白字符,请使用

if(zipCodeValidator.isValid(str.strip())){

最后,您的正则表达式只匹配大写字母。确保使用

允许所有情况
str.strip().toUpperCase()

或更改您的正则表达式:

private static Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);