在字符串中查找完全匹配

时间:2017-09-15 20:01:09

标签: c#

我想找到一个单词的完全匹配。这与我使用的相似:

ContactFirst

问题是,如果"Johnson"Johnson,则会返回匹配项。解决这个问题的正确方法是什么?基本上,我正在寻找的解决方案只有在JohnnyJohn时才能为John DoeCREATE TABLE dbo.Book( Id int NOT NULL CONSTRAINT PK_book PRIMARY KEY , Title varchar(30) NOT NULL , Price decimal(9,2) NOT NULL , Status bit NOT NULL , row_version rowversion NOT NULL ); INSERT INTO dbo.Book (Id, Title, Price, [Status]) VALUES(1, 'C# 6', 40.0, 0); GO CREATE PROC dbo.UpdateBookAvailability @Id int , @Rowversion rowversion , @Status bit AS UPDATE dbo.Book SET Status = @Status WHERE Id = @Id AND row_version = @RowVersion; IF @@ROWCOUNT < 1 BEGIN RAISERROR('book not avaiable', 16, 1); END; GO 返回正数。 }

3 个答案:

答案 0 :(得分:9)

我发现在类似的情况下使用正则表达式更容易。

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

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

答案 1 :(得分:0)

我不确定我是否理解正确。如果你想逐个比较两个字符串,可以使用字符串方法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,则返回此项,否则返回String.Emty

答案 2 :(得分:0)

        // 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;