Java:文件读取/写入

问题描述:

我试图从文件中读取并将所有美元值替换为欧元,例如,如果文件中的某处存在$ 30.25,则应将其转换为26.84E。我设法使其工作,但我不知道如何使它工作,例如,如果文本包含像$ 30.25的东西。 (最后注意点)。我使用字符串的替换方法,但如果使用replace(“。”,“”),它显然会删除所有的点,所以它不起作用。你能以其他方式帮助我吗?Java:文件读取/写入

预先感谢您。

+2

您是否尝试过 “由数字环绕的任何点”?看看关于正则表达式的教程。 – Gendarme

+0

该文件是您作为程序的结果创建并随后从中读入的内容吗?如果是这样,我认为最好是确定是什么导致了额外的句号,并纠正这个错误,而不是稍后检查 – Peter

+0

,那么你想要https://docs.oracle.com/javase/7/docs/ API /爪哇/郎/ String.html#replaceFirst(java.lang.String中,%20java.lang.String) –

你仍然可以使用替代方法,如果你可以隔离你首先要保持的发生,这可以用下面的例子String.split()

的进行使用正向后看分裂的句号。正面看,从落后Regex101的定义:

Regex101 Positive lookbehind description


private String replaceAllButFirstOccurrence(String text, String sequence){ 
    if(text.contains(sequence) && (text.indexOf(sequence) != text.lastIndexOf(sequence))){ 
     //There are at least 2 occurrences of the sequence 
     String[] substrings = text.split("(?<=\\.)", 2); //Split in 2 
     /* 
      Input is now segmented in 2: 
       [0] - The first sub string containing the first occurrence 
       [1] - The second sub string containing the rest of the input that can be modified 
     */ 
     return substrings[0] + substrings[1].replaceAll("\\.", ""); 
    } 
    return text; 
} 

样品:

$100 -> $100 
$200.00 -> $200.00 
$250.00. -> $250.00 
$300.00.. -> $300.00