java - If conditions using regex -
what regex satisfy following situation:
if (string starts letter (one or more)) must followed . or _ (not both) else no match example (imagine have list of values matched, being tested):
public static boolean matches(string k) { (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; } this code matches of below
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")); but fails on
system.out.println(matches("weirdusr")); // matches when should not simplified, i'd recognize that
final string = "(?:[a-za-z]+)[\\._]" + key; final string b = "^[\\._]?" + key; when string starts character, separator no longer optional, else, if string starts separator, optional
to satisfy mentioned condition, try:
srt.matches("[a-za-z]+(\\.[^_]?|_[^\\.]?)[^\\._]*")
Comments
Post a Comment