什么正则表达式将有助于满足以下情况:
if (string starts with a letter (one or more))
it must be followed by a . or _ (not both)
else
no match
示例(假设我有一个要匹配的值列表,正在测试):
public static boolean matches(String k) {
for (final String key : protectedKeys) {
final String OPTIONAL_SEPARATOR = "[\\._]?";
final String OPTIONAL_CHARACTERS = "(?:[a-zA-Z]+)?";
final String OR = "|";
final String SEPARATED = OPTIONAL_CHARACTERS +
OPTIONAL_SEPARATOR + key + OPTIONAL_SEPARATOR
+ OPTIONAL_CHARACTERS;
String pattern = "(" + key + OR + SEPARATED + ")";
if (k.matches(pattern)) {
return true;
}
}
return false;
}
此代码与以下所有内容匹配
System.out.println(matches("usr"));
System.out.println(matches("_usr"));
System.out.println(matches("system_usr"));
System.out.println(matches(".usr"));
System.out.println(matches("system.usr"));
System.out.println(matches("usr_"));
System.out.println(matches("usr_system"));
System.out.println(matches("usr."));
System.out.println(matches("usr.system"));
System.out.println(matches("_usr_"));
System.out.println(matches("system_usr_production"));
System.out.println(matches(".usr."));
System.out.println(matches("system.usr.production"));
但是失败了
System.out.println(matches("weirdusr")); // matches when it should not
简化,我想认识到这一点
final String a = "(?:[a-zA-Z]+)[\\._]" + key;
final String b = "^[\\._]?" + key;
当字符串以字符开头时,分隔符不再是可选的,否则,如果字符串以 a 分隔符开头,它现在是可选的