java - 如何确保字符串具有某种格式
问题描述
目前我有这样的代码
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();
}
}
我希望代码只允许创建有效的部门名称
例子:
- 初级管理
- 高级管理人员
但是,现在我面临一个问题,管理一词可以放在任何地方并且仍然被认为是有效的
例子:
- 管理
- 管理初级
当我创建部门时,如何确保部门名称后面的管理一词是必需的?谢谢。
解决方案
只需将此功能更改为:
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()
。
推荐阅读
- sh - 在linux中的变量中获取上一个目录路径
- android - 带有换行内容的相对布局
- angular - 用户单击要删除的其他产品,但默认情况下它会从购物车中删除最后一个产品在离子电子商务应用程序中
- java - ReplyingKafkaTemplate 是否阻塞?
- java - 如何捕捉 FileNameExtensionFilter 并为它们制定逻辑?
- c# - DbContext 模型构建器中的用户详细信息
- php - 目前卡在虚拟连接 PHP 和 SQL SERVER 2012
- laravel - 重构 Laravel 查询
- json - 在 ajax request.didnt 中发现 302 未命中 post 操作。如何解决这个问题
- android - GestureListenerManagerImpl 为 null 使 webview 崩溃