Search code examples
c#regexstringcontain

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 true for foo2:

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!"
if(line.Contains("%")){}

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


Solution

  • 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 %.