1

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

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

4

3 回答 3

0

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

srt.matches("[a-zA-Z]+(\\.[^_]?|_[^\\.]?)[^\\._]*")
于 2012-06-04T21:56:26.937 回答
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使用强制失败进行任何更改(?!)

于 2012-06-05T14:44:03.147 回答
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;
        }
    }
于 2012-06-04T22:23:20.107 回答