depecheSoul
depecheSoul

Reputation: 956

How to totally compare a string with regular expression in objective C

I am trying to see via reg ex if the user gave the correct input(user should give complex number), and dependent on the input the program should give some action.

So far I have three reg expressions for comparison:

@"([-]?[1-9][0-9]*[+|-][1-9][0-9]*i)+"
@"([-]?[1-9][0-9]*)+"
@"([-]?[1-9][0-9]*[i])+"

In the case that I want to see if the complex number is given correctly, I use first reg ex.

If it is not given correctly I want to use other two expressions to see if the user used abbreviations for input.

The problem is if the user gives 3i in the program i will get that this is real number, because of the reg ex. Reg ex is testing if the part of the string is correct, and I want to know if the entire string is correct.

For example if i type 3i3 and if I use third expression, i will get that the result is true, and I want it to be true only for 3i.

Upvotes: 1

Views: 71

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726489

If you want to make a regex that matches the entire string, add ^ and $ anchors to it:

@"^([-]?[1-9][0-9]*[+|-][1-9][0-9]*i)+$"
@"^([-]?[1-9][0-9]*)+$"
@"^([-]?[1-9][0-9]*[i])+$"
  • ^ at the beginning means that the match must start at the beginning of the input string
  • $ at the end means that there must be no extra characters in the input after the match

Upvotes: 1

Related Questions