如何确保字符串具有特定格式

时间:2018-10-10 08:04:21

标签: java string

目前我有这样的代码

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();
    }

}

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

示例:

  • 初级管理
  • 高级管理人员

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

示例:

  • 管理
  • 初级管理人员

在创建部门时,如何确保部门名称后面必须有“管理”一词?谢谢。

2 个答案:

答案 0 :(得分:2)

两种方法

a。在 StringUtils 中使用startsWith()endsWith(),或者仅使用startsWith()提供的endsWith()String

boolean endsWith = StringUtils.endsWith("Managemet") && !StringUtils.startsWith("Managemet");

b。使用正则表达式.*?Management$,在此表达式中,使用.*?包含空格和其他特殊字符

String str ="Test Management";
String regex = ".*?Management$";
System.out.println(str.matches(regex));

答案 1 :(得分:2)

只需将此功能更改为此:

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()轻松检查的异常,它可能会变得过于复杂和难以理解。