String matching
How to match the string "Net Amount" (between Net and Amount there can be any number of spaces, including zero) with net amount
?
Spaces between these two words can be any whitespace and exact matching of two string should be there. But Net Amount (first string with spaces) can be part of any string like Rate Net Amount
or Rate开发者_如何学Python CommissionNet Amount.
The match should be case-insensitive.
Use regular expressions. Have a look at the System.Text.RegularExpressions
namespace, namely the Regex
class:
var regex = new RegEx("net(\s+)amount", RegexOptions.IgnoreCase);
// ^^^^^^^^^^^^^^^
// pattern
The argument string is what is called the regular expression pattern. Regular expression patterns describe what strings will match against it. They are expressed with a specialized syntax. Google for regular expressions
and you should find plenty of information about regexes.
Usage example:
bool doesInputMatch = regex.IsMatch("nET AmoUNT");
// ^^^^^^^^^^^^^^^^^
// test input
If you just want to check if a match exists, use IsMatch:
using System;
using System.Text.RegularExpressions;
class Program
{
public static void Main()
{
string s = "Net Amount";
bool isMatch = Regex.IsMatch(s, @"Net\s*Amount",
RegexOptions.IgnoreCase);
Console.WriteLine("isMatch: {0}", isMatch);
}
}
Update: In your comments it sounds like the string you want to search for is only known at runtime. You could try building the regular expression dynamically, for example something like this:
using System;
using System.Text.RegularExpressions;
class Program
{
public static void Main()
{
string input = "Net Amount";
string needle = "Net Amount";
string regex = Regex.Escape(needle).Replace(@"\ ", @"\s*");
bool isMatch = Regex.IsMatch(input, regex, RegexOptions.IgnoreCase);
Console.WriteLine("isMatch: {0}", isMatch);
}
}
You can use
Regex.IsMatch(SubjectString, @"net\s*amount", RegexOptions.Singleline | RegexOptions.IgnoreCase);
You can use a Regular Expression: Net.*Amount
.
using System.Text.RegularExpressions;
Regex regex = new Regex("Net.*Amount");
String s = "Net Amount";
Match m = emailregex.Match(s);
// Now you have information in m about the matching string.
精彩评论