java - 尝试匹配 Java 中几乎重复的模式

标签 java regex

我正在尝试为我的大学项目匹配一个非常具体的模式。不幸的是我被困住了。模式如下:

  • A word or number of length 1 or 2 followed by ,.
  • This is repeated for four times and then followed by ; instead of ,.
  • This whole thing repeats itself for exactly four times but without ; at the end.

示例是:

SR,SR,SR,AR;0,11,22,33;SG,1,23,DG;SY,BY,CY,DY
36,AR,CR,DR;SB,10,16,22;SG,13,BG,DG;SY,0,20,BY

而这些不应该匹配(查找逗号和分号):

SR,SR;SR,AR;0,11,22,33;SG,1,23,DG;SY,BY,CY,DY
36,AR,CR,DR,SB,10,16,22;SG,13,BG,DG;SY,0,20,BY

我得到的最接近的是

((([ABCDS][RBGY])|\d{1,2})[,;]){16}

但这确实符合上面的反面例子。

这是我当前的解决方法:

public boolean matching(String arguments) {
    String[] strings = arguments.split(";");
    if (strings.length != 4) return false;
    for (String s : strings) {
        String[] strings1 = s.split(",");
        if (strings1.length != 4) return false;
        for (String s1 : strings1) {
            if (!s1.matches(POSITION_PATTERN)) return false;
        }
    }
    return true;
}

但是,这不是一个理想的解决方案,而且效率很低。

最佳答案

您可以尝试使用以下模式:

(?:[ABCDS][RBGY]|\d{1,2})(?:,(?:[ABCDS][RBGY]|\d{1,2})){3}(?:;(?:[ABCDS][RBGY]|\d{1,2})(?:,(?:[ABCDS][RBGY]|\d{1,2})){3}){3}

说明:

(?:[ABCDS][RBGY]|\d{1,2})          match two letter or 1-2 digits
(?:,(?:[ABCDS][RBGY]|\d{1,2})){3}  followed by a comma and another two letters or
                                   1-2 digits, that quantity 3 times
(?:;                               then match semicolon
    (?:[ABCDS][RBGY]|\d{1,2})(?:,(?:[ABCDS][RBGY]|\d{1,2})){3}){3}
                                   followed by the previous pattern 3 more times

Demo

关于java - 尝试匹配 Java 中几乎重复的模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54368901/

相关文章:

java - Maven 的 WAR 依赖

java.lang.IndexOutOfBoundsException : Index: 38, 大小:38

python - 为什么 Python 中同时存在 sre 和 re 模块?

java - 丢弃字符的前导和尾随系列,但保留相同的字符

java程序疑惑

java - List.fill(int)(method()) 等同于 Java?

regex - 如何在oracle列中查找连续重复的字符

c - rm * 的 posix 正则表达式是什么?

javascript正则表达式案例

java - AtomicReference getAndSet 和其他此类方法中字段 valueOffSet 的作用是什么