havakok havakok - 26 days ago 7x
C# Question

Finding if a charter exist alone in a string C#

I want to find (in VS C#) if a string contains a character (for example '%') with no immediate repetitions.

For example "i have % alone and this is fine=>%%" . I want to find any string that contains a single '%' (even a couple times) regardless of adjoined "%%" occurrences.

The following will obviously not work, and will give


string foo1="% I want to find this string";
string foo2="I don't want to find this string because the char %% is not alone";
string foo3="I%want%to%find%this%as%well!"

I have tried to understand how to apply regular expression here tono avail.


Moving my comment here:

You might just as well use a non-regex approach for that:

if (s.Contains("%") && !s.Contains("%%"))

If you need to use a regex, you may use negative lookarounds with Regex.IsMatch:

if(Regex.IsMatch(line, @"(?<!%)%(?!%)")) {}

See this regex demo.

The (?<!%) negative lookbehind will fail the match if a % is preceded with a % and the (?!%) negative lookahead will fail the match if the % is followed with %.