简体   繁体   English

java中的正则表达式; 用其他字符替换字符

[英]regex in java; replace character with other character

I have a String as below:我有一个字符串如下:

String toModify= 
    "T600XX MAG4292505 0120153P+000000335.20GBP+000000001.0000+0000335.2001+00000 +000001";

I have to replace 01 written before 2nd dot with 95 .我必须用95替换第二个点之前写的01

Expected result of the modified String should be:修改后的字符串的预期结果应该是:

String modified= 
    "T600XX MAG4292505 0120153P+000000335.20GBP+000000095.0000+0000335.2001+00000 +000001";

Please note:请注意:

  1. Position of 01 is not fixed from starting position 01位置从起始位置不固定
  2. It is fixed that 01 will come just before 2nd .固定01将在 2nd 之前出现.
  3. It is fixed that 01 will come after 2nd +固定01会在 2nd +
  4. It is fixed that 01 will come after GBP and GBP will come only one time in the String固定01会在GBP之后,而GBP在String中只会出现一次

I used below code and it is working fine我使用了下面的代码,它工作正常

int indexOf2ndDot=toModify.indexOf(".",toModify.indexOf("GBP"));   
toModify =toModify.substring(0,indexOf2ndDot-2)+"95"+toModify.substring(indexOf2ndDot);

If is there any better solution using regex, please suggest.如果使用正则表达式有更好的解决方案,请提出建议。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM