Ernesto
Ernesto

Reputation: 944

regex for digits between dots

Hi I am struggling with regex in Java for those scenarios:

  String testtt = "aha.comment.1.app"; // should pass
  String testtt2 = "aha.comment1.app"; // should fail

My logical proposition was:

 String regex = ".\\.[0-9]\\..+";

but it's not working...

I want to have a regex that will just check if in the whole string there is a digit/number wrapped with two dots e.g .1., .22. and also the characters can stay before and after.

other test scenarios:

a.1.b.c.d.2.a // should pass
a.2.b.c2.a.1. // should not pass

any hints?

of course i am using testtt.matches(regex)

Upvotes: 2

Views: 847

Answers (3)

The fourth bird
The fourth bird

Reputation: 163632

Assuming the string can not start and end with a dot, one option is to use a positive lookahead to assert dot-digits-dot

^(?=.+\.\d+\.)[^.\n\r]+(?:\.[^.\n\r]+)+$

Regex demo

In Java if you are using matches, and with the doubled backslashes

String regex = "(?=.+\\.\\d+\\.)[^.\\n\\r]+(?:\\.[^.\\n\\r]+)+";

If the dot can be anywhere, and there must be digits-dot-digits and either chars a-z or digits between the dots:

 ^(?!.*(?:[a-z][0-9]|[0-9][a-z]))(?!.*?\.\.)[a-z0-9.]*\.\d\.[a-z0-9.]*$

See another Regex demo

Upvotes: 3

MonkeyZeus
MonkeyZeus

Reputation: 20757

Something like this would work:

^\.?(?:\d+|[a-z]+)(?:\.(?:\d+|[a-z]+))*\.?$

This assumes you are performing a verification of a period-separated string which can only have digits or letters between the periods, not both.

https://regex101.com/r/nCoIQu/1

Upvotes: 1

Raffaele
Raffaele

Reputation: 26

.*\.[0-9]*\..*

these regex may help you

Upvotes: 0

Related Questions