Regex: complex number
Question: This is my regex for imaginary number:
[0-9]{0,}\d\.[0-9]{0,}\d[i]|[0-9]{0,}\d[i]
It only accepts an imaginary number with a pure complex part.
When my parser is encountered, for example String im = "2i";
, it gets 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;
}
Is there any way to do this with a regex straight away? For example, any decimal number followed by the letter "i" is converted to another string - complex(0, number)
?
Here's an example of what you can 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 gets messy with your function expression (i.e. complex(0, 1,2)
could be a problem), you can:
- remove that part of the template or
- surround the backlink with some delimiter in replacement, eg.
"complex(0, \"$1\")"
etc.