Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex: Complex Number

Question: This is my regular expression for an imaginary number:

[0-9]{0,}\d\.[0-9]{0,}\d[i]|[0-9]{0,}\d[i]

It only takes an imaginary number with a pure complex part.

When my parser is encountering, for example String im = "2i";, it is converted to String z = "complex(0, 2)" //complex(re, im) - like this:

Matcher m = pattern.regex.matcher(exp);     //String exp = "2i + 5"

if(m.find())
{
  String key = m.group();                   //String key = "2i"
  int type = pattern.token;

   if(type == COMPLEX) 
   {
    key = key.replaceAll("i", "");          // key = "2"
    exp = m.replaceFirst("");               // exp = "5"
    exp = "complex(0," + key +")" + exp;    //exp = "complex(0,2) + 5"
   }

   return exp;
}

Can i somehow do this with the regular expression at once? E.g any decimal number followed by the letter " i " is converted to another String - complex(0, number) ?

like image 400
quiZ___ Avatar asked Jan 29 '26 17:01

quiZ___


1 Answers

Here's an example of what you may want to try, with String#replaceAll:

// testing integers, comma-separated and floats
String test = "1 * 2i + 3.3i / 4.4 ^ 5,555i * 6,666 + 7,777.7i / 8,888.8";
System.out.println(
    test
    .replaceAll(
       //| group 1: whole expression
       //| | any 1+ digit
       //| |  | optional comma + digits
       //| |  |       | optional dot + digits
       //| |  |       |         | final "i"
        "(\\d+(,\\d+)?(\\.\\d+)?)i", 
        "complex(0, $1)"
    )
);

Output

1 * complex(0, 2) + complex(0, 3.3) / 4.4 ^ complex(0, 5,555) * 6,666 + complex(0, 7,777.7) / 8,888.8

Note

If the comma part will mess with your function expression (i.e. complex(0, 1,2) might be a problem) you can either:

  • remove that part of the pattern, or
  • surround the back-reference with some delimiter in the replacement, e.g. "complex(0, \"$1\")", etc.
like image 196
Mena Avatar answered Feb 01 '26 08:02

Mena