如何在C#中使用通配符模式进行字符串比较

sha*_*mim 10 c# asp.net

C#是否提供了将字符串与通配符模式进行比较的任何方法.或者我可以说我想找一个"Like Operator"来进行字符串比较.假设我有一个字符串.我也有一个段落,我想在这个parapgraph上找到字符串,但是怎么做.在SQL中我们只能使用LIKE运算符.

任何建议和回复都很感激.

Gab*_*abe 12

通配符是一种复杂的野兽(一种正则表达式),但听起来你想要这种Contains方法.你可以这样做paragraph.Contains(sentence).


Qui*_*son 6

String有一个Contains应该足够的方法,返回一个boolean

"Big string that represents a paragraph".Contains("that");
Run Code Online (Sandbox Code Playgroud)

包含方法MSDN页面中的示例:

// This example demonstrates the String.Contains() method
using System;

class Sample 
{
    public static void Main() 
    {
    string s1 = "The quick brown fox jumps over the lazy dog";
    string s2 = "fox";
    bool b;
    b = s1.Contains(s2);
    Console.WriteLine("Is the string, s2, in the string, s1?: {0}", b);
    }
}
/*
This example produces the following results:

Is the string, s2, in the string, s1?: True
*/
Run Code Online (Sandbox Code Playgroud)

如果你需要更高级的匹配,那么Regex可能是正确的路线,但是从你说的我认为包含的例子中可以正常工作.


小智 5

您可以使用Regex定义通配符.这些不像DOS那样完全有效,但功能更强大.看到:

http://msdn.microsoft.com/en-us/library/ms228595(VS.80).aspx