You could implement it like this:
input =~ /[+-]?\d*[+-]?\d*i/
The issue is that you're not being strict enough about what may come before the
i, as part of the complex number.
Your current code is just saying "include anything before
i as part of the match". Therefore the match always begins at the start of the string - so the method returns
nil if there's no match).
To explain my regex:
[+-] means "either a
[+-]? means "zero or one of the above".
\d means "any digit" (0, 1, 2, ..., 9).
\d* means "zero or more of the above".
So in other words, this will match anything like:
But won't match arbitrary other strings that contain an
Your tests #9 and #10 also fail (but pass with my implementation!) - but you are not seeing this, because the test terminates upon its first failure. (It would be better to split each assertion into a separate test, for this reason.)
Your method will return
0, because it still just matches "anything followed by
My method will return
nil, because it only matches "numbers" followed by
-3+4i); not arbitrary characters.
Your method should work here, except for a small mistake: Because your regex ends in
i* instead of just
i, it matches "0 or more
is". In other words, it will still match strings that don't contain an
My method does not have this mistake.
Normally however, if you want to convert a string to a complex number, you could just do:
...And if that raises an exception, then the string was an invalid format.
"num: -35+46i" would normally be invalid however; so if you want to accept these then you do indeed need to perform some sort of regex lookup first.