Java 正则表达式:复数
问题:这是我对虚数的正则表达式:Java 正则表达式:复数,java,regex,parsing,Java,Regex,Parsing,问题:这是我对虚数的正则表达式: [0-9]{0,}\d\.[0-9]{0,}\d[i]|[0-9]{0,}\d[i] 它只需要一个具有纯复数部分的虚数 当我的解析器遇到问题时,例如String im=“2i”,它被转换为String z=“complex(0,2)”//complex(re,im)-如下所示: Matcher m = pattern.regex.matcher(exp); //String exp = "2i + 5" if(m.find()) { String
[0-9]{0,}\d\.[0-9]{0,}\d[i]|[0-9]{0,}\d[i]
它只需要一个具有纯复数部分的虚数
当我的解析器遇到问题时,例如String im=“2i”
,它被转换为String z=“complex(0,2)”//complex(re,im)
-如下所示:
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;
}
我能马上用正则表达式做这个吗?例如,任何后跟字母“i”的十进制数字都会转换为另一个字符串-
复数(0,数字)
?下面是一个您可能想要尝试的示例,使用字符串#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)"
)
);
输出
1 * complex(0, 2) + complex(0, 3.3) / 4.4 ^ complex(0, 5,555) * 6,666 + complex(0, 7,777.7) / 8,888.8
注意
如果逗号部分会干扰函数表达式(即复杂(0,1,2)可能是个问题),您可以:
- 移除图案的该部分,或
- 在替换项中用一些分隔符将后面的引用括起来,例如,
等“complex(0,\“$1\””