-1

I am trying to write a boolean function to support double colons :: only for a string. It should reject any string with non-consecutive colon or more than two consecutive colons. The appearance of double colons can be any number. I can write regex which supports double colons but I don't know how to reject so many combinations of non-consecutive and consecutivec colons. Any idea is appreciated!

Valid inputs: Customer::Table, Customer::Table::Sub

Invalid inputs: Customer:Table, Customer::Table:Sub, Customer::::Table

dashenswen
  • 540
  • 2
  • 4
  • 21

1 Answers1

3

Here is one line option using String#matches:

String input = "Customer::Table::Sub";
if (input.matches("[^:]+(?:::[^:]+)*")) {
    System.out.println("MATCH");
}

Demo

Here is an explanation of the regex used:

[^:]+          match one or more non colon characters
(?:            start non capturing group
    ::[^:]+    match :: again followed by one or more non :
)*             the group occurring zero or more times
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360