user1119859 user1119859 - 11 days ago 9
Java Question

How to disallow "." (dot) as first character in regular expressions

I want to create to regular expression that allows all combinations of characters and digits and also dots but not a dot at the beginning. So valid strings could be "1.2.3" or "1.b.34d" or something. But I want to disallow strings like "." or ".1.2.3".

I'm trying with

[^.]{0,1}[ a-zA-Z_\\-\\.0-9]*


but this doesn't work. Anyone any better idea?

Answer

You may use

s.matches("(?!\\.)[\\w\\s.-]*")

The pattern will match a string that does not start with a . due to the negative lookahead (?!\\.) and contains zero or more word chars (letters, digits or underscores - \w), whitespaces (\s), . or - symbols. Note you do not need ^/\A, nor $/\z since the String#matches() method anchors the pattern by default.

NOTE: To make this pattern Unicode-aware, add (?U) (a Pattern.UNICODE_CHARACTER_CLASS embedded flag option) at the start of the pattern: s.matches("(?U)(?!\\.)[\\w\\s.-]*").