Java regular expression to match the pattern for equals sign between two or more words that has an exclamatory as a delimeter between the ranges

You can use

^(?:\w+=\w+!)*\w+=\w+!?$

In Java

String regex = "^(?:\\w+=\\w+!)*\\w+=\\w+!?$";

The pattern matches:

  • ^ Start of string
  • (?:\w+=\w+!)* Optionally repeat 1+ word chars = 1+ word chars and !
  • \w+=\w+!? Match 1+ word chars = 1+ word chars and optional !
  • $ End of string

Regex demo

String[] strings = {
    "Name=John!Age=25!Gender=M",
    "Name=John!Name2=Sam!Name3=Josh",
    "Name=John!Name2=Sam!Name3=Josh!",
    "N=J!A=25!",
    "a=ba=b",
    "Name!John=Name2+Sam=",
    "Name=John=",
    "Name=John!!",
    "Name=John-"
};

for (String s : strings) {
    if (s.matches("(?:\\w+=\\w+!)*\\w+=\\w+!?")) {
        System.out.println("Match: " + s);
    } else {
        System.out.println("No match: " + s);
    }
}

Output

Match: Name=John!Age=25!Gender=M
Match: Name=John!Name2=Sam!Name3=Josh
Match: Name=John!Name2=Sam!Name3=Josh!
Match: N=J!A=25!
No match: a=ba=b
No match: Name!John=Name2+Sam=
No match: Name=John=
No match: Name=John!!
No match: Name=John-