为什么string.replace确实只替换每一次出现?

时间:2016-05-24 13:18:28

标签: java replace

我的代码:

String newBody = response.body.replace(";\"\";", ";\"|||\";");

其中response.body是这样的:

"9.3";"";"";"";"";"";

执行后,结果如下:

"9.3";"|||";"";"|||";"";"|||";

我希望如此:

"9.3";"|||";"|||";"|||";"|||";"|||";

我认为它与替换的逻辑有关,因为我这样做:;"";希望它被替换为:;"|||";而每个被替换的字符串都是新的开头一。但我仍然希望它能被处理......

3 个答案:

答案 0 :(得分:3)

在您的示例中,replace方法正在寻找;"";。所以它会从第一个分号开始。但是,在第一次之后,它会找到它跳过的"",然后再次找到该模式。这是因为你的结尾是分号。你应该使用的是:

String newBody = response.body.replace(";\"\"", ";\"|||\"");

答案 1 :(得分:2)

更改此行:

String newBody = response.body.replace(";\"\";", ";\"|||\";");

要:

String newBody = response.body.replace(";\"\"", ";\"|||\"");

答案 2 :(得分:2)

为避免消耗每场比赛的尾随import java.net.URL; import java.util.HashMap; import java.util.ResourceBundle; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.control.PasswordField; import javafx.scene.control.TextField; import javafx.stage.Stage; public class PopupController extends AbstractController implements Initializable { @FXML private TextField usernameTF; @FXML private PasswordField passwordPF; @FXML private Button connectBtn; private Stage stage = null; private HashMap<String, Object> result = new HashMap<String, Object>(); @Override public void initialize(URL url, ResourceBundle rb) { connectBtn.setOnAction((event)->{ result.clear(); result.put("username", usernameTF.getText()); result.put("password", passwordPF.getText()); closeStage(); }); } public HashMap<String, Object> getResult() { return this.result; } /** * setting the stage of this view * @param stage */ public void setStage(Stage stage) { this.stage = stage; } /** * Closes the stage of this view */ private void closeStage() { if(stage!=null) { stage.close(); } } } 但仍然检查它是否存在,请使用正则表达式进行预测:

;