简体   繁体   中英

Regular expression causing my failing unit tests. Why?

I am having a really tough time with regular expressions. Mine is causing my unit test to fail. I have tried it a couple of different ways without success. Maybe I am going about it wrong. I need it to either use one word (Trumpet) or two words with a space (French Horn).

Property that I am having an issue with.

public string Name
    {
        get { return _name; }
        set
        {
            string source = propTI.ToTitleCase(value.Trim());
            string pattern = "^[A-Z][a-z]*\\s[A-Z][a-z]*$";
            if (Regex.IsMatch(source, pattern))
                _name = source;
            else
            {
                throw new ArgumentException("Name must have proper case!");
            }
        }
    }

I have also tried "^([AZ][az] \\s) $" as a pattern.

Constructor:

public Instrument() : this(DefaultName, DefaultCategory) { }

Unit Test:

  [TestMethod]   
  public void Instrument_Name_IsValid()
    {
        var na = "french";
        var goodna = "French";
        var inst = new Instrument();
        inst.Name = na;
        Assert.AreEqual(goodna, inst.Name);
    }

What should I use for a regular expression? Since these are clearly not working?

Casimir et Hippolyte有答案:

^[A-Z][a-z]*(?:\\s[A-Z][a-z]*)*$

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