hzxu
hzxu

Reputation: 5823

NSString: Regular Expression for blabla.DDD+DDDD where D is digit

I need a regular expression to check if a string has this pattern:

[some random characters].DDD+DDDD

it can start with random characters, but it ends with a dot . then three digits, then a plus sign followed by four digits. How can I construct the regular expression and check if a NSString has this pattern?

Thanks!

Upvotes: 0

Views: 640

Answers (3)

rmaddy
rmaddy

Reputation: 318924

The expression ^[^.]*\.[0-9]{3}\+[0-9]{4}$ should do it.

The ^ means start of string [^.]*\. means zero or more non-period characters followed by a period [0-9]{3} means 3 digits (0-9) \+ means a plus [0-9]{4} means 4 digits The $ means end of string

Upvotes: -1

neodym
neodym

Reputation: 21

This should be what you are looking for.

NSString *regex = @"(^[^.]*\.[0-9]{3}\+[0-9]{4}$)";
NSPredicate *pred = [NSPRedicate predicateWithFormat:@"SELF MATCHES %@", regex];
if ([pred evaluateWithObject:mystring])
{
  //do something
}

There are many good Regex Generators to test your regular expressions. E.x.: http://rubular.com

Upvotes: 2

borrrden
borrrden

Reputation: 33423

The correct regex is ^[^.]*\.[0-9]{3}\+[0-9]{4}$

Both of the other answers forgot to escape certain characters.

Upvotes: 0

Related Questions