如何解析大写单词的字符串

时间:2009-01-06 16:09:30

标签: c# regex

我有这个字符串:" Mimi loves Toto and Tata hate Mimi so Toto killed Tata"

我想编写一个代码,只打印以大写字母开头的单词,避免重复

输出应该像

Mimi
Toto
Tata

我试图这样做,但即使没有出现任何错误,我也确定错了。

我写的代码:

static void Main(string[] args)
        {
            string s = "Memi ate Toto and she killed Tata Memi also hate Biso";
            Console.WriteLine((spliter(s)));
        }



        public static string spliter(string s)
        {

            string x = s;
            Regex exp = new Regex(@"[A-Z]");
            MatchCollection M = exp.Matches(s);

            foreach (Match t in M)
            {

                while (x != null)
                {
                    x = t.Value;  
                }

            }
            return x;
        }


    }
}

思想:

如果我将字符串拆分成数组,然后应用正则表达式逐字检查它然后打印结果怎么办?我不知道 - 任何人都可以帮我制作这段代码吗?

12 个答案:

答案 0 :(得分:7)

我根本不知道C#/ .net正则表达式lib,但这个正则表达式模式会这样做:

\b[A-Z][a-z]+

\ b表示匹配只能从单词的开头开始。如果你想允许单字大写,请将+更改为*。

编辑:你想要匹配“麦当劳”吗?

\b[A-Z][A-Za-z']+

如果您不想匹配'如果它只出现在字符串的末尾,那么就这样做:

\b[A-Z][A-Za-z']+(?<!')

答案 1 :(得分:6)

我不确定我为什么发布这个......

   string[] foo = "Mimi loves Toto and Tata hate Mimi so Toto killed Tata".Split(' ');
            HashSet<string> words = new HashSet<string>();
            foreach (string word in foo)
            {
                if (char.IsUpper(word[0]))
                {
                    words.Add(word);
                }
            }

            foreach (string word in words)
            {
                Console.WriteLine(word);
            }

答案 2 :(得分:5)

C#3

        string z = "Mimi loves Toto and Tata hate Mimi so Toto killed Tata";
        var wordsWithCapital = z.Split(' ').Where(word => char.IsUpper(word[0])).Distinct();
        MessageBox.Show( string.Join(", ", wordsWithCapital.ToArray()) );

C#2

        Dictionary<string,int> distinctWords = new Dictionary<string,int>();
        string[] wordsWithInitCaps = z.Split(' ');
        foreach (string wordX in wordsWithInitCaps)
            if (char.IsUpper(wordX[0]))
                if (!distinctWords.ContainsKey(wordX))
                    distinctWords[wordX] = 1;
                else
                    ++distinctWords[wordX];                       


        foreach(string k in distinctWords.Keys)
            MessageBox.Show(k + ": " + distinctWords[k].ToString());

答案 3 :(得分:2)

我建议使用string.split将字符串分隔成单词,然后只打印char.IsUpper(word [0])为真的单词。

this

这样的东西

答案 4 :(得分:2)

使用此正则表达式

<强>([A-Z] [A-Z] +)

说明:

[A-Z]    [a-z]+
  |        |
Single   Multiple(+)
  |        |
  C      apital   -> Capital

试用正则表达式here

答案 5 :(得分:1)

解。请注意使用内置字符串拆分器。你可以通过检查第一个字符是否在'A'和'Z'之间来替换toupper的东西。删除我留给您的重复项(如果需要,请使用哈希集)。

static void Main(string[] args)
    {
        string test = " Mimi loves Toto and Tata hate Mimi so Toto killed Tata";
        foreach (string j in test.Split(' '))
        {
            if (j.Length > 0)
            {
                if (j.ToUpper()[0] == j[0])
                {
                    Console.WriteLine(j);
                }
            }
        }
        Console.ReadKey(); //Press any key to continue;
    }

答案 6 :(得分:1)

由于其他人已经发布了这么多答案,我觉得我没有违反任何家庭作业规则来表明这一点:

//set up the string to be searched
string source =
"First The The Quick Red fox jumped oveR A Red Lazy BRown DOg";

//new up a Regex object.
Regex myReg = new Regex(@"(\b[A-Z]\w*)");

//Get the matches, turn then into strings, de-dupe them
IEnumerable<string> results =
    myReg.Matches(source)
    .OfType<Match>()
    .Select(m => m.Value)
    .Distinct();

//print out the strings.
foreach (string s in results)
    Console.WriteLine(s);
  • 要了解Regex类型,您应该开始here
  • 要了解Linq内存中查询方法,您应该启动here

答案 7 :(得分:1)

适当的正则表达式:\b\p{Lu}\p{L}*

var result = 
    Regex.Matches(input, @"\b\p{Lu}\p{L}*")
    .Cast<Match>().Select(m => m.Value);

答案 8 :(得分:0)

string foo = "Mimi loves Toto and Tata hate Mimi so Toto killed Tata";
char[] separators = {' '};
IList<string> capitalizedWords = new List<string>();
string[] words = foo.Split(separators);
foreach (string word in words)
{
    char c = char.Parse(word.Substring(0, 1));

    if (char.IsUpper(c))
    {
        capitalizedWords.Add(word);
    }
}

foreach (string s in capitalizedWords)
{
    Console.WriteLine(s);
}

答案 9 :(得分:0)

大卫B的答案是最好的,他考虑到塞子这个词。一票投票。

在他的回答中添加一些内容:

        Func<string,bool,string> CaptureCaps = (source,caseInsensitive) => string.Join(" ", 
                new Regex(@"\b[A-Z]\w*").Matches(source).OfType<Match>().Select(match => match.Value).Distinct(new KeisInsensitiveComparer(caseInsensitive) ).ToArray() );


        MessageBox.Show(CaptureCaps("First The The  Quick Red fox jumped oveR A Red Lazy BRown DOg", false));
        MessageBox.Show(CaptureCaps("Mimi loves Toto. Tata hate Mimi, so Toto killed TaTa. A bad one!", false));


        MessageBox.Show(CaptureCaps("First The The  Quick Red fox jumped oveR A Red Lazy BRown DOg", true));
        MessageBox.Show(CaptureCaps("Mimi loves Toto. Tata hate Mimi, so Toto killed TaTa. A bad one!", true));


class KeisInsensitiveComparer : IEqualityComparer<string>
{
    public KeisInsensitiveComparer() { }

    bool _caseInsensitive;
    public KeisInsensitiveComparer(bool caseInsensitive) { _caseInsensitive = caseInsensitive; }


    // Products are equal if their names and product numbers are equal.
    public bool Equals(string x, string y)
    {

        // Check whether the compared objects reference the same data.
        if (Object.ReferenceEquals(x, y)) return true;

        // Check whether any of the compared objects is null.
        if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
            return false;



        return _caseInsensitive ? x.ToUpper() == y.ToUpper() : x == y;
    }

    // If Equals() returns true for a pair of objects,
    // GetHashCode must return the same value for these objects.

    public int GetHashCode(string s)
    {
        // Check whether the object is null.
        if (Object.ReferenceEquals(s, null)) return 0;

        // Get the hash code for the Name field if it is not null.
        int hashS = s == null ? 0 : _caseInsensitive ? s.ToUpper().GetHashCode() : s.GetHashCode();

        // Get the hash code for the Code field.
        int hashScode = _caseInsensitive ? s.ToUpper().GetHashCode() : s.GetHashCode();

        // Calculate the hash code for the product.
        return hashS ^ hashScode;
    }

}

答案 10 :(得分:0)

    static Regex _capitalizedWordPattern = new Regex(@"\b[A-Z][a-z]*\b", RegexOptions.Compiled | RegexOptions.Multiline);

    public static IEnumerable<string> GetDistinctOnlyCapitalizedWords(string text)
    {
        return _capitalizedWordPattern.Matches(text).Cast<Match>().Select(m => m.Value).Distinct();
    }

答案 11 :(得分:-1)

function capitalLetters() {
  var textAreaId = "textAreaId";
  var resultsArray = $(textAreaId).value.match( /\b[A-Z][A-Za-z']+/g );
  displayResults(textAreaId, resultsArray);
}