检查单词是以大写还是小写开头

时间:2016-02-12 18:54:33

标签: c# regex visual-studio

我需要编写一个程序,当它在文本中找到 $(document).ready(function() { $('form').on('submit', function(e){ e.preventDefault(); I want to retrieve the parameters here, but how? Do I actually need to send them as hidden input? } }); }); 时,它应该检查下一个单词,如果它以大写字母(大写)开头,那么它将在“。”之前的单词。如果没有列表框(以小写开头)然后在另一个列表框中的前面的单词 我有这个到目前为止,但似乎没用:

"."

}

3 个答案:

答案 0 :(得分:2)

You can use String.IndexOf(char, int) to find the dot and then use Char.IsUpper(char) to find out if it is uppercase or lowercase.

答案 1 :(得分:1)

You could probably do it with a regex.

(?<!\S)(\w+)\s+\.(?=\s+(\w+)(?!\S))

Expanded

 (?<! \S )
 ( \w+ )                       # (1)
 \s+ 
 \.
 (?=
      \s+ 
      ( \w+ )                       # (2)
      (?! \S )
 )

In a while loop, on each match check if capture group 2 starts with a capital.
if so put capture 1 into list box 1, if not, put capture 1 in list box 2.

Added

Note that this is trying to emulate your code functionality.
Therefore it uses a lookahead for the second value, which in turn can be
the first value in the next value dot value pair.

C# sample

string f1_txt = @"abc . DEF . ghi . JKL some, junk, some, junk, mno . PQR some junk stu . VWX";
Regex Rx = new Regex(@"(?<!\S)(\w+)\s+\.(?=\s+(\w+)(?!\S))");

Match _matchData = Rx.Match( f1_txt );
while (_matchData.Success)
{
    if ( char.IsUpper(_matchData.Groups[ 2 ].Value[ 0 ] ) )
        Console.WriteLine("Add {0} to ListBox1", _matchData.Groups[ 1 ].Value);
    else
        Console.WriteLine("Add {0} to ListBox2", _matchData.Groups[ 1 ].Value);
    _matchData = _matchData.NextMatch();
}
return;

Output

Add abc to ListBox1
Add DEF to ListBox2
Add ghi to ListBox1
Add mno to ListBox1
Add stu to ListBox1

答案 2 :(得分:0)

Char.IsUpper()显然是最简单,最实用的方式。但是,如果你想给面试官留下深刻印象,那就行了:

bool StartsWithUpper(string word)
{
    return Enumerable.Range(65, 26).Contains((int)word[0]);
}