Alagappan Ramu
Alagappan Ramu

Reputation: 2358

Regular Expression to match Alphanumeric values with at least one number

I want to match a pattern which contains a hyphen between alphanumeric characters with at least one number on either side of the hyphen.

I have tried the following Pattern in Java. But some of the below mentioned patterns are not matched properly.

Pattern alpha_numeric = Pattern.compile("([a-zA-Z0-9]+\\-[0-9]+)|([0-9]+\\-[a-zA-z0-9]+)");

Ideally, some patterns which should match are:

a-45
45-a
45-45
a-aaa4
aaa4a-bbb5
a4aa-a etc

The following pattern should not match:

a-a
b-b etc

How should I go about fixing it?

Upvotes: 0

Views: 627

Answers (3)

Origineil
Origineil

Reputation: 3118

You have to account for the "at least one digit" requirement, which in regex translates to

\d+ - requiring the escape extra \ in a Java string

Example:

    public void test() {
    final List<String> testCases = Arrays.asList("a-45",
            "45-a",
            "45-45",
            "a-aaa4",
            "aaa4a-bbb5",
            "a4aa-a etc",
            "a-a",
            "b-b");

    final String regex = "[a-z]*\\d+[a-z]*";
    final String leftMatch = regex + "-.*";
    final String rightMatch = ".*-" + regex;

    for (String string : testCases) {
      System.out.println(string + " : " + string.matches(leftMatch + "|" + rightMatch));
    }
}

Result:

a-45 : true
45-a : true
45-45 : true
a-aaa4 : true
aaa4a-bbb5 : true
a4aa-a etc : true
a-a : false
b-b : false

Upvotes: 0

Vlad
Vlad

Reputation: 1197

$ sed -r 's/([a-zA-Z0-9]*-[a-zA-Z]*[0-9][a-zA-Z0-9]*|[a-zA-Z]*[0-9][a-zA-Z0-9]*-[a-zA-Z0-9]*)/{\1}/g' file
{a-45}
{45-a}
{45-45}
{a-aaa4}
{aaa4a-bbb5}
{a4aa-a}
a-a
b-b
-
a-
-a
{-4}
{4-}

Upvotes: 1

Some patterns are not matched because of regex definition.

Your regex says:

(alphanumeric string)-(numbers string) OR (numbers string)-(alphanumeric string)
  1. Pattern 45-45 is not matched cause it is (numbers string)-(numbers string)
  2. Pattern a-aaa4 is not matched cause it is (alphanumeric string)-(aplhanumeric string)

You should cover more cases and rewrite your regex.

Upvotes: 0

Related Questions