Emel Uras Emel Uras - 1 year ago 136
C# Question

How to check if a text contains a set of char using regex in C#

I would like to understand if my message includes a fixed set of chars like


What I am trying is:

if (!loggingEvent.RenderedMessage.Contains("[0-9]:[0-9]"))

but it is not working as I want. How can I fix it? It is in C#.


The whole string is like:

The server IP is ->!

Answer Source

A regex approach will look like

if (!Regex.IsMatch(loggingEvent.RenderedMessage, "[0-9]+:[0-9]+"))

Note that String.Contains does not support regex. Also, [0-9] matches 1 digit while you probably want to allow 1 or more (that is what + ensures).

See the online C# demo also extracting that substring:

var s = "The server IP is ->!"; 
var result = Regex.Match(s, @"[0-9]+:[0-9]+");
if (result.Success)
    Console.WriteLine("No match!");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download