priyam singh
priyam singh

Reputation: 115

Java Regex to validate group field pattern example - abc.def.gh1

I am just writing some piece of java code where I need to validate groupId (maven) passed by user. For example - com.fb.test1.

I have written regex which says string should not start and end with '.' and can have alphanumeric characters delimited by '.'

[^\.][[a-zA-Z0-9]+\\.{0,1}]*[a-zA-Z0-9]$

But this regex not able to find out consecutive '.' For example - com..fb.test. I have added {0,1} followed by decimal to restrict it limitation to 1 but it didnt work.

Any leads would be highly appreciated.

Upvotes: 0

Views: 71

Answers (1)

The fourth bird
The fourth bird

Reputation: 163577

The quantifier {0,1} and the dot should not be in the character class, because you are repeating the whole character class allowing for 0 or more dots, including { , } chars.

You can also exclude a dot to the left using a negative lookbehind instead of matching an actual character that is not a dot.

In Java you could write the pattern as

(?<!\\.)[a-zA-Z0-9]+(?:\\.[a-zA-Z0-9]+)+[a-zA-Z0-9]$

Note that the $ makes sure that that match is at the end of the string.

Regex demo

Upvotes: 0

Related Questions