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) ?
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:
"complex(0, \"$1\")", etc.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With