这是字符串:
+CUSD: 1,"Your current Bank Account balance is Tk 17,370.37. Your available Bank Account balance is Tk 17,370.37.",15
cusd:旁边的数字,帐户余额金额,以及最后一位数字,在这种情况下15将全部变化。
以下正则表达式格式是否正确?
Match match = new Regex("\\+CUSD: (\\d+),\"Your current Bank Account balance is Tk (.+) Your available Bank Account balance is Tk (.+)\",(.+)\\r\\n").Match(input);
while (match.Success)
{do something;}
答案 0 :(得分:1)
您可以使用
@"\+CUSD: (\d+),""Your current Bank Account balance is Tk ([\d,.]+)\. Your available Bank Account balance is Tk ([\d.,]+)\."",(\d+)"
请参阅regex demo
在此,我建议将.+
简化为\d+
(1位或更多位数)或[\d.,]+
(匹配1位数,点或句点)。如果您使用.+
,它会匹配换行符以外的1个以上字符,并会导致大量不必要的回溯,这可能会降低长输入的效果。
此外,使用带有@"..."
的原始字符串文字,这样您就不必使用具有特殊正则表达式字符的双重转义,应将其视为文字(例如\+
),或者使用声明速记字符像\d
这样的课程。
这是C# demo:
var s = "+CUSD: 1,\"Your current Bank Account balance is Tk 17,370.37. Your available Bank Account balance is Tk 17,370.37.\",15";
var mtch = Regex.Match(s, @"\+CUSD: (\d+),""Your current Bank Account balance is Tk ([\d,.]+)\. Your available Bank Account balance is Tk ([\d.,]+)\."",(\d+)");
if (mtch.Success) {
Console.WriteLine(string.Format("CUSD: {0}", mtch.Groups[1].Value));
Console.WriteLine(string.Format("Bank Account balance: {0}", mtch.Groups[2].Value));
Console.WriteLine(string.Format("Your available Bank Account balance: {0}", mtch.Groups[3].Value));
Console.WriteLine(string.Format("Last number: {0}", mtch.Groups[4].Value));
}