如果条件使用正则表达式

时间:2012-06-04 21:38:06

标签: java regex

正则表达式有助于满足以下情况:

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分隔符开头,则它现在是可选的

3 个答案:

答案 0 :(得分:0)

要满足上述条件,请尝试:

srt.matches("[a-zA-Z]+(\\.[^_]?|_[^\\.]?)[^\\._]*")

答案 1 :(得分:0)

如果这对任何人都有帮助,我也可以这样做

    for (final String key : protectedKeys) {

        final String separator = "[\\._]";
        final String textSeparator = "(" + "^(?:[a-zA-Z]+)" + separator + ")";
        final String separatorText = "(?:" + separator + "(?:[a-zA-Z]+)$" + ")";

        final String OR = "|";

        final String azWithSeparator = textSeparator + "?" + key + separatorText + "?";
        final String optionalSeparatorWithoutAZ = separator + "?" + key + separator + "?";

        String pattern = "(" + key + OR + azWithSeparator + OR + optionalSeparatorWithoutAZ + ")";

        if (k.matches(pattern)) {
            return true;
        }
    }

答案 2 :(得分:0)

if (string starts with a letter (one or more))
  it must be followed by a . or _ (not both)
else
  no match

可以用正则表达式编写:

^[A-Za-z]+[._]

正则表达式符合规范(你没有说明允许遵循的内容)。

如果不满足条件,匹配将按定义失败,因此强制失败else无需进行任何(?!)更改。