簡體   English   中英

在字符串中查找完全匹配

[英]Find exact match inside a string

我想找到一個單詞的完全匹配。 這類似於我正在使用的:

string TheSearchString = "John";
ContactFirst.IndexOf(TheSearchString, StringComparison.CurrentCultureIgnoreCase);

問題是,如果ContactFirst"Johnson"則將返回一個匹配項。 解決這個問題的正確方法是什么? 基本上,我正在尋找一個不會對JohnsonJohnny產生積極影響的解決方案,僅當它是JohnJohn Doe

我發現在類似於此的條件下使用正則表達式會更容易。

string ContactFirst = "sometext Johnson text";
string TheSearchString = "John";

var match = Regex.IsMatch(ContactFirst, $@"\b{TheSearchString}\b", RegexOptions.IgnoreCase) );

我不確定我是否正確理解。 如果要一一比較兩個字符串,可以使用字符串方法Equals

string TheSearchString = "John";
bool result = ContactFirst.Equals(TheSearchString , StringComparison.Ordinal);

如果您想獲取內容字符串

private string GetStringOnContent(string content, string searchText)
        {
            string findValue = string.Empty;
            int strIndex = content.IndexOf(searchText);
            if(strIndex > 0 )
            {
                findValue = content.Substring(strIndex, searchText.Length );
            }

            return findValue;
        }    

var findStr = GetStringOnContent("This is content that has John as a part of content", "John");

如果包含searchText,則返回this,否則返回String.Emty

        // using System.Text.RegularExpressions;

        string TheSearchString = "John";
        string ContactFirst = "Johnson";

        // any number of whitespaces around the searched-pattern permitted but no other characters
        string pattern1 = @"^[ \t\r\n]*\b" + TheSearchString + @"\b[ \t\r\n]*$";

        // exactly the searched-pattern with no surrounding whitespace permitted (same as equals)
        string pattern2 = @"^\b" + TheSearchString + @"\b$";

        // the searched-pattern as a stand-alone word anywhere 
        string pattern3 = @"\b" + TheSearchString + @"\b";

        Regex r = new Regex(pattern3, RegexOptions.IgnoreCase);
        bool result = r.IsMatch(ContactFirst);
        int foundAt = -1;
        // the string index of the first match from the Matches collection
        if (result)
            foundAt = r.Matches(ContactFirst)[0].Index;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM