Reputation: 263723
I'm currently developing a SMS application in vbnet. One problem I encountered is when the sim card runs out of load. So I make a function that checks the balance if sending a message failed for 3 times. Now the problem is how can i parse or get the value from the string. I know this can be done in ReGex (or you can suggest me if you have a better technique for this). This is the reply from the service provider:
Your current balance as of 02/15/2012 00:17 is P1.00 valid til...
I need to get the P1.00
from the string. And the possible valid format of the balance is:
So as you can see, the pattern has a monetary symbol of P
(or sometimes Php
) and followed by a numeric value. Sometimes it has a white space between the monetary symbol and the value. The pattern also has two decimal places. Now how can i do this using ReGex?
I cannot show some codes since I have no (even a single) idea where should i start from. I really need your help.
Upvotes: 3
Views: 869
Reputation: 19308
If you know that the response will be in that form, you might consider validating the whole message at the same time.
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()
Amount will include both the prefix and the number.
Here's an explanation of the regex.
^ (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)
Hope this helps.
Upvotes: 1
Reputation: 11627
From a quick test in Expresso, this should do it for you:
(?i)[P|Php](?: ?)(\d*\.\d\d) valid
And as explanation:
(?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
Upvotes: 1