简体   繁体   中英

VBNet RegEx Pattern

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:

  • P1.50
  • P10.00
  • P100.00
  • P 100.75
  • P 1.00
  • Php 1.00
  • Php10.50

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM