首页 > 解决方案 > 如何确保字符串具有某种格式

问题描述

目前我有这样的代码

public class Department {

    public static final String MESSAGE_DEPARTMENT_CONSTRAINTS =
            "Department names should only contain alphanumeric characters and spaces, and it should not be blank\n"
            + "Department names should start with a name, followed by 'Management'";


    public static final String DEPARTMENT_VALIDATION_REGEX = "[\\p{Alnum}][\\p{Alnum} ]*";

    public final String fullDepartment;

    public Department(String department) {
        requireNonNull(department);
        checkArgument(isValidDepartment(department), MESSAGE_DEPARTMENT_CONSTRAINTS);
        fullDepartment = department;
    }

    /**
     * Returns true if a given string is a valid department name.
     */
    public static boolean isValidDepartment(String test) {
        return (test.matches(DEPARTMENT_VALIDATION_REGEX) && (test.indexOf("Management") >= 0));
    }


    @Override
    public String toString() {
        return fullDepartment;
    }

    @Override
    public boolean equals(Object other) {
        return other == this // short circuit if same object
                || (other instanceof Department // instanceof handles nulls
                && fullDepartment.equals(((Department) other).fullDepartment)); // state check
    }

    @Override
    public int hashCode() {
        return fullDepartment.hashCode();
    }

}

我希望代码只允许创建有效的部门名称

例子:

但是,现在我面临一个问题,管理一词可以放在任何地方并且仍然被认为是有效的

例子:

当我创建部门时,如何确保部门名称后面的管理一词是必需的?谢谢。

标签: javastring

解决方案


只需将此功能更改为:

public static boolean isValidDepartment(String test) {
  return test.matches(DEPARTMENT_VALIDATION_REGEX) 
              && test.endsWith("Management") 
              && !test.equals("Management");
}

如果您认为需要更复杂的检查,您还可以将部门验证正则表达式更改为:

public static final String DEPARTMENT_VALIDATION_REGEX = "(\\p{Alnum}+ )+Management";

public static boolean isValidDepartment(String test) {
  return test.matches(DEPARTMENT_VALIDATION_REGEX);
}

请注意,这仍然允许"Management Management"并且"M8n8g3m3nt Management"因为您使用了\\p{Alnum}. 如果您只需要字母字符,请使用\\p{Alpha}. 如果你想捕捉"Management Management"你可能想要做的异常:

public static boolean isValidDepartment(String test) {
  return test.matches(DEPARTMENT_VALIDATION_REGEX) 
              && !test.equals("Management Management");
}

您应该能够通过正则表达式完成所有操作,但是对于您可以轻松检查的一个异常,可能会变得过于复杂且难以阅读.equals()


推荐阅读