gpt4 book ai didi

java - 在字符串中多次匹配某个模式

转载 作者:行者123 更新时间:2023-12-02 08:38:58 28 4
gpt4 key购买 nike

目的是通过某种分布函数来替换 double ,即像这样转换字符串

0.5 * x + 0.5 * y

转换为字符串:

IntPMF[(0;0.5)(1;0.5)] * x + IntPMF[(0;0.5)(1;0.5)] * y

我编写了以下函数:

    public static String replaceDoubles(String stoEx) {
Pattern p = Pattern.compile("(\\d+(?:\\.[0-9]\\d*))");
Matcher m = p.matcher(stoEx);
while (m.find()) {
double d = Double.parseDouble(m.group(1));
String dStr = String.valueOf(d);
String[] parts = dStr.split("\\.");
int lower = Integer.valueOf(parts[0]);
int upper = lower + 1;
double decimalPart = d - lower;
decimalPart = round(decimalPart, 2);
double rest = round(1 - decimalPart, 2);
String replacement = "IntPMF[(" + lower + ";" + rest + ")(" + upper + ";" + decimalPart + ")]";
stoEx = stoEx.replaceAll(m.group(1), replacement);
}
return stoEx;
}

问题是,使用这个函数我得到以下输出(对于上面提到的字符串):

IntPMF[(0;IntPMF[(0;0.5)(1;0.5)])(1;IntPMF[(0;0.5)(1;0.5)])] * x + IntPMF[(0;IntPMF[(0;0.5)(1;0.5)] (1;IntPMF[(0;0.5)(1;0.5)])] * y

double 0.5被替换了好几次......

任何有关解决方案的建议将不胜感激。谢谢!

最佳答案

如果我正确理解了要求,你可以使用这样的东西。要舍入值并获得解释,建议使用 DecimalFormatter。避免为此使用 JDK 内部库。

public static void main( String[] args )
{
DecimalFormat df = new DecimalFormat( "0.00" );

//0.52 -> IntPMF[(0;0.48)(1;0.52)]
String stoEx = "0.5 * x + 0.32222* y";
Pattern p = Pattern.compile( "(\\d+\\.\\d+)" );
Matcher m = p.matcher( stoEx );
String result = "";
StringJoiner stringJoiner = new StringJoiner( "+" );
String[] splitString = stoEx.split( "\\+" );
for( String subString: splitString )
{
if( m.find() )
{
String fracPart = m.group( 1 ).split( "\\." )[1];
String fracOne = df.format( 1 - ( Integer.parseInt( fracPart ) / Math.pow( 10.0, fracPart.length() ) ) );
String fracTwo = df.format( ( Integer.parseInt( fracPart ) / Math.pow( 10.0, fracPart.length() ) ) );
String resultEx = "IntPMF[(" + 0 + ";" + fracOne + ")(" + 1 + ";" + fracTwo + ")]";
result = subString.replaceFirst( m.group( 1 ), resultEx );
stringJoiner.add( result );
}
}
System.out.println( stringJoiner.toString() );
}

关于java - 在字符串中多次匹配某个模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61503099/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com