I want to write a regex pattern that starts with a class name and has dot between class names and ends with a class name
each class name,starts with a letter.it is like class import in java,
I wrote this pattern but it is too complex and slow for validating and I think it does not work properly
^([a-zA-Z]([0-9]|_|[a-zA-Z])*)(([a-zA-Z]([0-9]|_|[a-zA-Z])*)|\\.)*([a-zA-Z]([0-9]|_|[a-zA-Z])*)$
for example my input string should be like this: “com.casp.common.StringUtils”
Firstly, simplification:
can be combined as
and actually it has a shorthand representation
so your regex can first be simplified to this equivalent form:
Now, we could further simplify by removing some redundant capture groups, and turn on case-insensitive matching:
Of course this regex is incorrect, it matches
a....b, for instance.The problem is because the
\.is an “alternative”, which should not be, as a dot is required between each component. So it should probably transformed to:but it is still incorrect because it won’t match
a.b, because of the leading part. We need to remove it:and probably rearrange it such that the repeating part is at the end, not the start: