vibhor vaish vibhor vaish - 7 months ago 48
Java Question

This pattern matches for input 123456789.2.2.2 , which it should not

Your task is to match the pattern abc.def.ghi.jkl , where each variable a,b,c,d,e,f,g,h,i,j,k,l can be any single character except the newline.

For above question i am matching the input to regex :

"([^\\n]{3}(.)){3}([^\\n]{3})"
// this is the regex pattern i am using currently


what am i doing wrong, please help me correct the above regex so that it does not match to the input i have provided in the title.Currently it matches to it somehow.Although i have provided 3 it is apparently matching to more than 3 characters.

Answer

. has a special meaning in regular expression patterns.

If you want to get a "simple dot", you need to quote/escape it (as "\\.").

And that special meaning is (under normal configuration) "any character except line breaks", which exactly matches your other condition, so you can simplify this to

"(...)\\.(...)\\.(...)\\.(...)"