Code Snippet to Convert Word Tense

Here is a useful code snippet to convert the tense of a word from single to plural and vise versa. The code uses a series of regular expression to examine the word and convert it using the correct grammar.
public string MakePlural(string name)
{
    Regex plural1 = new Regex("(?<keep>[^aeiou])y$");
    Regex plural2 = new Regex("(?<keep>[aeiou]y)$");
    Regex plural3 = new Regex("(?<keep>[sxzh])$");
    Regex plural4 = new Regex("(?<keep>[^sxzhy])$");

    if(plural1.IsMatch(name))
        return plural1.Replace(name, "${keep}ies");
    else if(plural2.IsMatch(name))
        return plural2.Replace(name, "${keep}s");
    else if(plural3.IsMatch(name))
        return plural3.Replace(name, "${keep}es");
    else if(plural4.IsMatch(name))
        return plural4.Replace(name, "${keep}s");

    return name;
}

public string MakeSingle(string name)
{
    Regex single1 = new Regex("(?<keep>[^aeiou])ies$");
    Regex single2 = new Regex("(?<keep>[aeiou]y)s$");
    Regex single3 = new Regex("(?<keep>[sxzh])es$");
    Regex single4 = new Regex("(?<keep>[^sxzhy])s$");

    if(single1.IsMatch(name))
        return single1.Replace(name, "${keep}y");
    else if(single2.IsMatch(name))
        return single2.Replace(name, "${keep}");
    else if(single3.IsMatch(name))
        return single3.Replace(name, "${keep}");
    else if(single4.IsMatch(name))
        return single4.Replace(name, "${keep}");

    return name;
}
~ Paul
 
 
 
Published Friday, September 03, 2004 1:18 PM by pwelter34
Filed under:

Comments

# re: Code Snippet to Convert Word Tense

It's "number", not "tense". Tense is a verb thing.
And it's "singular", not "single".
And this is really about spelling, not grammar.
And this code won't work for some nouns ("passerby" for example). You'd need a dictionary of nonstandard ones in addition to your existing code to really get this right.

Friday, September 03, 2004 3:18 PM by Anon

# re:Code Snippet to Convert Word Tense

^_^,Pretty Good!

Sunday, April 10, 2005 7:06 AM by TrackBack

# re: Code Snippet to Convert Word Tense

Thanks Paul. This code works quite well when converting the most common plural words to the singular form.

Saturday, September 01, 2007 2:37 PM by Charlie

# re: Code Snippet to Convert Word Tense

Hi Paul,

Some words such as gasses, phases, phrases etc are not trimmed correctly. I am trying to improve your code.

Saturday, September 01, 2007 2:47 PM by Charlie

# re: Code Snippet to Convert Word Tense

Thursday, April 09, 2009 8:23 PM by nick_c4tlid