-1

I am trying to check if a string matches the pattern of a complex number with the format x+yi or x-yi. My regex for this purpose is ^\d+(\.\d+)?[-\+]\d+(\.\d+)?i and it works just fine on regexr (regexr.com/572bb).

Here is my minimal example in java:

public class ExampleClass {
    public static void main(){
        String comp = "3+5i";
        System.out.println(comp.matches("^\\d+(\\.\\d+)?[-\\+]\\d+(\\.\\d+)?i"));
    }

It throws the above exception. Here it is in full:

Exception in thread "main" java.util.regex.PatternSyntaxException: Dangling meta character '+' near index 0

The "+" it's complaining about is this one: [-\\+] but it doesn't seem like it's dangling since I escaped it. I am a beginner, so I would appreciate any help I can get. Thank you!

gowner
  • 327
  • 1
  • 4
  • 11
  • @WJS Fixed that :) That wasn't the issue though – gowner Jun 20 '20 at 00:31
  • It's working for me. Please see code [**here**](https://onlinegdb.com/Bk_Qt0qp8). –  Jun 20 '20 at 00:33
  • @Mandy8055 I'm trying to understand this part: `[-+\\\\]` Doesn't this just say "allow as many '-' as you want" and then it escapes two semicolons? I'm very confused. – gowner Jun 20 '20 at 00:33
  • @Mandy8055 I'm sorry for probably being annoying but the way I learned about regex, I thought square brackets means "match any character in the set" and in order to allow the "+" character, I have to escape it because it's a metacharacter. Does regex work differently in Java or am I just being kind of dumb? EDIT: didn't see your edit :D – gowner Jun 20 '20 at 00:38
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/216310/discussion-between-flo-klar-and-mandy8055). – gowner Jun 20 '20 at 00:42
  • You don't need to escape. `"^\\d+(\\.\\d+)?[-+]\\d+(\\.\\d+)?i"` will work. –  Jun 20 '20 at 00:57
  • Other than missing an end semi-colon, it worked fine for me. – WJS Jun 20 '20 at 02:28
  • You don't want an optional minus sign before the real part of the number? – Cary Swoveland Jun 20 '20 at 03:11

2 Answers2

-1

To represent complexes x + yi, x-yi, you could do it like this

String comp = "3+5i";
System.out.println(comp.matches("^[0-9]+([.][0-9]+)?[+,-][0-9]+([.][0-9]+)?[i]$"));
xxce10xx
  • 79
  • 4
  • Thank you for your help! Unfortunately, your solution doesn't allow me to input doubles or multi-digit numbers like "283.482+28.382i". – gowner Jun 20 '20 at 00:30
  • It also matches `"3,5i"`. –  Jun 20 '20 at 00:54
  • @Flo Klar, You are right, I did not think about the floating numbers, the expression would be `^[0-9]+([.][0-9]+)?[+,-][0-9]+([.][0-9]+)?[i]$` – xxce10xx Jun 20 '20 at 01:20
-1

The issue was nothing to do with that expression at all. I used String.split("+"); elsewhere in my code and neglected to escape that "+".

For posterity: Escape metacharacters when using String.split();.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
gowner
  • 327
  • 1
  • 4
  • 11