ATavares ATavares - 8 days ago 6
Java Question

Regex semicolon and words

i am facing some dificulties because of some regex expression in java. I want a expression the validates that one or more words are valid and are delimited by semicolon or not.

Examples:

VF;VM - Good
VF;GM - Bad
VF,VM - Bad
VF;VM;IF - Good
VF,VM;IF - Bad


I tried this one:

String regex = "(\\bVM\\b|\\bVF\\b|\\bTV\\b|\\bIM\\b|\\bIF\\b)|\\;";


But dont work....

If you can help me i will be thankfull

Answer

Basically, you want a list of the valid words, and then an optional repeated group starting with a ; and the list of valid words:

String regex = "^(?:\\b(?:VM|VF|TV|IM|IF)\\b)(?:;\\b(?:VM|VF|TV|IM|IF)\\b)*$";

That:

  • Uses ^ at the beginning and $ at the end to match the full input.
  • Starts with VM, VF, TV, IM, or IF with word boundary assertions on either side.
  • Then allows zero or more repeats with a ; in front of it. All of your examples involve at least two "words," though, so if that's a requirement, change the * (repeat zero or more times) to a + (repeat one or more times) on the second group.

...and actually, as Toto points out, since we're using anchors and defining a specific separator (;), we don't need the word boundaries, so simply

String regex = "^(?:VM|VF|TV|IM|IF)(?:;(?:VM|VF|TV|IM|IF))*$";

...is sufficient, and simpler.

Example on regex101 (as a JavaScript regex)

Tests:

class Example
{
    private static String regex = "^(?:VM|VF|TV|IM|IF)(?:;(?:VM|VF|TV|IM|IF))*$";

    public static void main (String[] args) throws java.lang.Exception
    {
        test("VF;VM", true);
        test("VF;GM", false);
        test("VF,VM", false);
        test("VF;VM;IF", true);
        test("VF,VM;IF", false);
    }

    private static void test(String str, boolean expectedResult) {
        boolean result = str.matches(regex);
        System.out.println(str + " -- " + (result ? "Good" : "Bad") + (result == expectedResult ? " - OK" : " - ERROR"));
    }
}

Live on ideone

Comments