Java:文件读/写

时间:2016-06-14 00:00:31

标签: java

我正在尝试从文件中读取并将所有美元值替换为欧元,例如,如果文件中的某个位置为30.25美元,则应将其转换为26.84E。我设法让它以某种方式工作,但我不知道如何让它工作,例如,如果文本包含30.25美元的东西。 (注意到最后的点)。我正在使用string的替换方法,但是如果我使用replace(“。”,“”),它显然会删除那里的所有点,所以它不起作用。你可以用其他任何方式帮助我这样做吗?

提前谢谢。

1 个答案:

答案 0 :(得分:0)

如果您可以先隔离要保留的事件,仍然可以使用替换方法,这可以使用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