[英]String matching
如何匹配字符串“凈金額”(凈值和金額之間可以有任意數量的空格,包括零)與net amount
?
這兩個單詞之間的空格可以是任何空格,兩個字符串的精確匹配應該在那里。 但凈金額(帶空格的第一個字符串)可以是任何字符串的一部分,如Rate Net Amount
或Rate CommissionNet Amount.
匹配應該不區分大小寫。
使用正則表達式。 看一下System.Text.RegularExpressions
命名空間,即Regex
類:
var regex = new RegEx("net(\s+)amount", RegexOptions.IgnoreCase);
// ^^^^^^^^^^^^^^^
// pattern
參數字符串是所謂的正則表達式模式 。 正則表達式模式描述了與之匹配的字符串。 它們用專門的語法表達。 谷歌regular expressions
,你應該找到有關regular expressions
大量信息。
用法示例:
bool doesInputMatch = regex.IsMatch("nET AmoUNT");
// ^^^^^^^^^^^^^^^^^
// test input
如果您只想檢查是否存在匹配項,請使用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);
}
}
更新:在您的評論中,您只想在運行時知道要搜索的字符串。 您可以嘗試動態構建正則表達式,例如:
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);
}
}
您可以使用
Regex.IsMatch(SubjectString, @"net\s*amount", RegexOptions.Singleline | RegexOptions.IgnoreCase);
您可以使用正則表達式: 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.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.