我目前正在vbnet中开发一个SMS应用程序。我遇到的一个问题是当SIM卡耗尽时。因此,如果发送消息失败3次,我会创建一个检查余额的函数。现在的问题是如何解析或从字符串中获取值。我知道这可以在ReGex中完成(或者你可以建议我,如果你有更好的技术)。这是服务提供商的回复:
Your current balance as of 02/15/2012 00:17 is P1.00 valid til...
我需要从字符串中获取P1.00
。并且可能的有效格式是:
如您所见,该模式的货币符号为P
(或有时为Php
),后跟数值。有时它在货币符号和值之间有一个空格。该模式还有两个小数位。现在我如何使用ReGex做到这一点?
我无法显示一些代码,因为我没有(甚至一个)想法我应该从哪里开始。我真的需要你的帮助。
答案 0 :(得分:1)
在Expresso的快速测试中,这应该适合你:
(?i)[P|Php](?: ?)(\d*\.\d\d) valid
作为解释:
(?i) == case insensitive
[p|php] == p or php
(?: ?) == a space, 0 or 1 repetitions, but do not capture the group
(\d*\.\d\d) == a digit any amount, followed by a . followed by two digits
答案 1 :(得分:1)
如果您知道答案将采用该格式,您可以考虑同时验证整个邮件。
Dim pattern = new Regex("^Your current balance as of \d{2}/\d{2}/\d{4} \d{2}:\d{2} is (?<amount>P(?:hp)?\s*\d+\.\d{2}) valid til")
Dim match = pattern.Match(input)
Dim amount = match.Groups("amount").ToString()
金额将包括前缀和数字。
以下是正则表达式的解释。
^ (Beginning of string)
Your current balance as of (Literal text)
\d{2}/\d{2}/\d{4} \d{2}:\d{2} (Date and time)
is (Literal string " is ")
(?<amount> (Begin named capture group)
P (Literal "P")
(?:hp)? (Optional non-capturing "hp")
\s* (0 or more whitespace characters)
\d+\.\d{2} (1 or more numbers, dot, two numbers
) (End named capture group)
valid til (Literal text)
希望这有帮助。