在句子中查找字符串表达式

最后发布: 2011-03-17 15:40:46


问题

我有一个三个单词的表达:“关门”,我想在一个句子中找到它。 由于它们被空间分隔开,因此最好的解决方案是。

c# .net vb.net
回答

如果您有字符串:

string sample = "If you know what's good for you, you'll shut the door!";

如果要查找句子中的位置,可以使用IndexOf方法。

int index = sample.IndexOf("shut the door");
// index will be 42

非-1的答案表示字符串已找到。 -1表示它在字符串中不存在。 请注意,搜索字符串(“关闭门”)区分大小写。


回答

使用Regex.Match方法中的build来匹配字符串。

string text = "One car red car blue car";
string pat = @"(\w+)\s+(car)";
// Compile the regular expression.
Regex r = new Regex(pat, RegexOptions.IgnoreCase);
// Match the regular expression pattern against a text string.
Match m = r.Match(text);
int matchCount = 0;
while (m.Success) 
{
   Console.WriteLine("Match"+ (++matchCount));
   for (int i = 1; i <= 2; i++) 
   {
      Group g = m.Groups[i];
      Console.WriteLine("Group"+i+"='" + g + "'");
      CaptureCollection cc = g.Captures;
      for (int j = 0; j < cc.Count; j++) 
      {
         Capture c = cc[j];
         System.Console.WriteLine("Capture"+j+"='" + c + "', Position="+c.Index);
      }
   }
   m = m.NextMatch();
}

http://msdn.microsoft.com/zh-CN/library/system.text.regularexpressions.regex.match(v=vs.71).aspx

http://support.microsoft.com/kb/308252


回答

if (string1.indexOf(string2) >= 0)
   ...


回答

空格没有什么特别的,它们只是字符,因此您可以找到这样的字符串,例如yuo会在句子中找到任何其他字符串,例如,如果需要位置,则使用“ indexOf”,或者,如果需要,则仅使用“ Contains”知道它是否存在。

例如

    string sentence = "foo bar baz";
    string phrase = "bar baz";

    Console.WriteLine(sentence.Contains(phrase)); // True


回答

这是一些C#代码,用于使用开始字符串和结束字符串点来查找子字符串,但是您可以将其用作基础并进行修改(即删除对结束字符串的需要)以仅找到您的字符串... 2个版本,其中一个仅用于查找子字符串的第一个实例,其他返回该子字符串和实际字符串的所有起始位置的字典。

    public Dictionary<int, string> GetSubstringDic(string start, string end, string source, bool includeStartEnd, bool caseInsensitive)
{
    int startIndex = -1;
    int endIndex = -1;
    int length = -1;
    int sourceLength = source.Length;
    Dictionary<int, string> result = new Dictionary<int, string>();

    try
    {
        //if just want to find string, case insensitive
        if (caseInsensitive)
        {
            source = source.ToLower();
            start = start.ToLower();
            end = end.ToLower();
        }

        //does start string exist
        startIndex = source.IndexOf(start);
        if (startIndex != -1)
        {
            //start to check for each instance of matches for the length of the source string
            while (startIndex < sourceLength && startIndex > -1)
            {
                //does end string exist?
                endIndex = source.IndexOf(end, startIndex + 1);
                if (endIndex != -1)
                {
                    //if we want to get length of string including the start and end strings
                    if (includeStartEnd)
                    {
                        //make sure to include the end string
                        length = (endIndex + end.Length) - startIndex;
                    }
                    else
                    {
                        //change start index to not include the start string
                        startIndex = startIndex + start.Length;
                        length = endIndex - startIndex;
                    }
                    //add to dictionary
                    result.Add(startIndex, source.Substring(startIndex, length));
                    //move start position up
                    startIndex = source.IndexOf(start, endIndex + 1);
                }
                else
                {
                    //no end so break out of while;
                    break;
                }
            }
        }
    }
    catch (Exception ex)
    {
        //Notify of Error
         result = new Dictionary<int, string>();
        StringBuilder g_Error = new StringBuilder();
        g_Error.AppendLine("GetSubstringDic: " + ex.Message.ToString());
        g_Error.AppendLine(ex.StackTrace.ToString());
    }
    return result;
}

public string GetSubstring(string start, string end, string source, bool includeStartEnd, bool caseInsensitive)
{
    int startIndex = -1;
    int endIndex = -1;
    int length = -1;
    int sourceLength = source.Length;
    string result = string.Empty;

    try
    {
        if (caseInsensitive)
        {
            source = source.ToLower();
            start = start.ToLower();
            end = end.ToLower();
        }

        startIndex = source.IndexOf(start);
        if (startIndex != -1)
        {
            endIndex = source.IndexOf(end, startIndex + 1);
            if (endIndex != -1)
            {
                if (includeStartEnd)
                {
                    length = (endIndex + end.Length) - startIndex;
                }
                else
                {
                    startIndex = startIndex + start.Length;
                    length = endIndex - startIndex;
                }
                result = source.Substring(startIndex, length);
            }
        }
    }
    catch (Exception ex)
    {
        //Notify of Error
        result = string.Empty;
        StringBuilder g_Error = new StringBuilder();
        g_Error.AppendLine("GetSubstring: " + ex.Message.ToString());
        g_Error.AppendLine(ex.StackTrace.ToString());
    }
    return result;
}


回答

您可能需要确保检查忽略两个短语的大小写。

string theSentence = "I really want you to shut the door.";
string thePhrase = "Shut The Door";

bool phraseIsPresent = theSentence.ToUpper().Contains(thePhrase.ToUpper());
int phraseStartsAt = theSentence.IndexOf(
    thePhrase, 
    StringComparison.InvariantCultureIgnoreCase);

Console.WriteLine("Is the phrase present? " + phraseIsPresent);
Console.WriteLine("The phrase starts at character: " + phraseStartsAt);

输出:

Is the phrase present? True
The phrase starts at character: 21