user723257
user723257

Reputation: 31

How to match exactly one period/dot but not at the end of the string?

Is it possible to have this done with one regex?

I need to match only those strings that have exactly one period/dot but the restriction is that that period/dot must not be at the end of the string.

Example:

abc.d will match

.abcd will match

abcd. will not match

Upvotes: 3

Views: 110

Answers (2)

manojlds
manojlds

Reputation: 301337

I really like @codaddict's answer, but how about something without Regex? ( C# code below )

if(a.Split('.').Length>2 || a.EndsWith("."))
    {
        Console.WriteLine("invalid");
    }

What I like is that it is much more clear that you don't want a string with two . and also a . should not be in the end. And this might actually be faster than using a regex.

Upvotes: 3

codaddict
codaddict

Reputation: 455282

Yes, you can do it in one regex:

^[^.]*\.[^.]+$

Upvotes: 7

Related Questions