Reputation: 23
I am trying to write a regex operation that will simply identify if there is only one period within a string.
For example, it will recognize arandomlink.online
and a@second#random-link.fr
, but it will not recognize an IPV4 IP Address with multiple periods, like 5.6.7.8
.
I'm currently using:
string URLpattern = @"\w*\.\w";
but the code above identifies IP addresses, which I don't want.
Anybody have any ideas? It's probably a very simple equation, but it's not coming to me right now. I can't figure out how to limit the equation to only identifying one period within the string, and not multiple. Because I'm working with Hash's and other things, it's best if I identify the URL's with the single period.
Upvotes: 2
Views: 661
Reputation: 627082
Since you are coding in C#, it makes sense to use a non-regex approach here (see Klaus Gütter's comment):
var ContainsOnlyOneDot = text.Count(c => c == '.') == 1;
If you have to do that with a regex, you can use
^[^.]*\.[^.]*$
See the regex demo. Details:
^
- start of string[^.]*
- zero or more chars other than .
\.
- a dot[^.]*
- zero or more chars other than a .
char$
- end of string.In C#, you can use
if (Regex.IsMatch(text, @"^[^.]*\.[^.]*$"))
{
Console.WriteLine("The string contains one dot only.");
}
else
{
Console.WriteLine("The string contains no dots or more than one dot.");
}
Upvotes: 1
Reputation: 79
What about something like this?
[^\s\.]+\.{1}[^\s\.]+
So one dot surrounded with negating sets of anything except a dot and a whitespace.
Upvotes: 0