在句子中找到一个字符串表达式

时间:2011-03-17 15:40:47

标签: c# .net vb.net

我喜欢三个字的表达:“关上门”,我想在一个句子中找到它。因为它们是空间分离的最佳解决方案。

6 个答案:

答案 0 :(得分:4)

如果您有字符串:

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表示字符串中不存在。请注意,搜索字符串(“关上门”)区分大小写。

答案 1 :(得分:2)

使用Regex.Match方法构建匹配字符串。

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/en-us/library/system.text.regularexpressions.regex.match(v=vs.71).aspx

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

答案 2 :(得分:0)

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

答案 3 :(得分:0)

空格没有什么特别之处,它们只是字符,所以你可以找到像这样的字符串,例如yuo会在你的句子中找到任何其他字符串,例如使用“indexOf”,如果你需要这个位置,或者只是“包含”如果你需要知道它是否存在。

E.g。

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

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

答案 4 :(得分:0)

下面是一些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;
}

答案 5 :(得分:0)

您可能希望确保检查忽略两个短语的情况。

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