简体   繁体   中英

C# Regular Expression. Uniqueness of the character

How can I check the uniqueness of the specified character in the line with regular expression. For example I have a line with different symbols. If there is only one dot(.) in the line then it must match with expression. I tried to do like this

public static void GetLines(List<string> lines)
    {
        Regex rx = new Regex(@"^.*\..*");
        foreach (var item in lines)
        {
            if (rx.IsMatch(item))
            {
                Console.WriteLine(item);
            }
        }
    }

This prints only lines where exists the dot(.) character. I think that this method will work if I write the expression like this @"^.*\\.{1}.*" But it doesn't work.

You need to modify your regex and write it like this if you want it to match to input that only and only contains single dot character.

Regex rx = new Regex(@"^[^.]*\.[^.]*$");

Explanation:

  • [^.]* ensures it matches any character zero or more times but not dot
  • . followed by a dot character
  • [^.]* again ensures it matches any character zero or more times but not dot

Similarly you can do it for any character just like dot.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM