模式XXYYZZ的正则表达式

我想验证一个字符串,它应该遵循XXYYZZX、Y、Z 可以是任何字母 az、AZ 或 0-9 的模式。

有效字符串示例:

RRFFKK
BB7733
WWDDMM
5599AA

无效:

555677
AABBCD

现在我正在使用正则表达式拆分字符串(?<=(.))(?!1)并迭代结果数组并检查每个子字符串的长度是否为 2。

String str = "AABBEE";
boolean isValid = checkPattern(str);

public static boolean checkPattern(String str) {
   String splited = str.split("(?<=(.))(?!1)");
   for (String s : splited) {
       if (s.length() != 2) {
         return false;
       }
   }
   return true;
}

我想替换我的检查方式String#matches并摆脱循环,但无法提出有效的正则表达式。有人可以帮助someRegex在下面的代码段中放入什么吗?

public static boolean checkPattern(String str) {
    return str.matches(someRegex);
}

回答

您可以使用

s.matches("(p{Alnum})1(?!1)(p{Alnum})2(?!1|2)(p{Alnum})3")

请参阅正则表达式演示。

细节

  • A- 字符串的开始(隐含在 中String#matches) - 字符串的开始
  • (p{Alnum})1 - 一个字母数字字符(捕获到第 1 组中)和紧随其后的相同字符
  • (?!1) - 下一个字符不能与组 1 中的相同
  • (p{Alnum})2 - 一个字母数字字符(捕获到第 2 组中)和紧随其后的相同字符
  • (?!1|2) - 下一个字符不能与组 1 和组 2 中的相同
  • (p{Alnum})3 - 一个字母数字字符(捕获到第 3 组中)和紧随其后的相同字符
  • z- (隐含在String#matches) - 字符串的结尾。

RegexPlanet 测试结果:


回答

由于您知道有效模式的长度始终为六个字符,其中包含三对彼此不同的相等字符,因此一系列简短的显式条件可能比正则表达式更简单:

public static boolean checkPattern(String str) {
   return str.length() == 6 &&
          str.charAt(0) == str.chatAt(1) &&
          str.charAt(2) == str.chatAt(3) &&
          str.charAt(4) == str.chatAt(5) &&
          str.charAt(0) != str.charAt(2) &&
          str.charAt(0) != str.charAt(4) &&
          str.charAt(2) != str.charAt(4);
}


回答

以下对你有用吗?

^(([A-Za-zd])2(?!.*2)){3}$

看在线演示


  • ^ - 开始字符串锚。
  • (- 打开第一个捕获组。
    • ( - 打开第二个捕获组。
      • [A-Za-zd] - 任何字母数字字符。
      • ) - 关闭第二个捕获组。
    • 2 - 完全匹配刚刚捕获的内容。
    • (?!.*2) - 负前瞻以确保在其他地方不会使用相同的字符。
    • ) - 关闭第一个捕获组。
  • {3} - 重复以上三遍。
  • $ - 结束字符串锚。
  • (You could make the outer group non capturing and use `1`) but nice ++
  • @Thefourthbird, thanks, You're right. It is simpler this way.
    It wasn't obvious from the original description. For the record: the full simplified regex which works is:
    `^(?:([A-Za-zd])1(?!.*1)){3}$`

以上是模式XXYYZZ的正则表达式的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>