Home > Software engineering >  Java regular expression to match the pattern for equals sign between two or more words that has an e
Java regular expression to match the pattern for equals sign between two or more words that has an e

Time:01-17

I'm trying to write a regular expression that matches all the following given pattern examples -

1) Name=John!Age=25!Gender=M
2) Name=John!Name2=Sam!Name3=Josh
3) Name=John!Name2=Sam!Name3=Josh!

Basically there has to be an equals to sign between two words or numbers followed by an exclamatory and then the pattern repeats. the pattern can only end with an exclamatory or any alphabets or numbers or spaces but not the 'equals' sign or any other special characters

So these examples should not be matched -

1) Name!John=Name2 Sam=
2) Name=John=
3) Name=John!!
4) Name=John-

I'm very new to regular expressions and I just learnt a few basic things and I have this following regular expression written so far which doesn't fully satisfy my requirement ((?:\w |=)*)!

I'm still trying to modify my regular expression to match my requirement, any help/guidance will be very helpful.

CodePudding user response:

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-
  •  Tags:  
  • Related