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.
CodePudding user response:
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.");
}
CodePudding user response:
What about something like this?
[^\s\.] \.{1}[^\s\.]
So one dot surrounded with negating sets of anything except a dot and a whitespace.