String 用Java替换字符串中某个子字符串的数字

String 用Java替换字符串中某个子字符串的数字,string,replace,String,Replace,我目前正在努力提取字符串的某个子字符串并替换其内容。数字要精确。数字变了,所以我不能接受整个字符串。例如,我有一条消息,如 String message = "hi John. You have two contracts listed: TV-70002548 and FV-50006578. The first contract ends on March 15th. I will pay you a final a

我目前正在努力提取字符串的某个子字符串并替换其内容。数字要精确。数字变了,所以我不能接受整个字符串。例如,我有一条消息,如

String message = "hi John. You have two contracts listed: 
                  TV-70002548 and FV-50006578. The first contract 
                  ends on March 15th. I will pay you a final amount of 350 $."
在这个字符串中,我有一组不同的数字,但我只想提取合同号并重写它们,比如TV-70002548->TV-seven-null-null-two-five-four-8

我写了一个方法,提取V之后的所有数字-因为这个字符对于字符串中的合同号是唯一的:

   private String replaceContractNo(String pMessage, String pInput, String pOutput) {
        String contractno;
        contractno = pMessage.substring(pMessage.indexOf("V-")-2);
        return contractno.replaceAll(pInput, pOutput);
    }
稍后我想用单词替换数字,如:

replaceContractNo(pMainMessage,"0"," null")
replaceContractNo(pMainMessage,"1"," one")
这不起作用,因为每次都会写出消息。这个问题有简单的解决办法吗


谢谢

这就是你想要做的吗

str1.replaceAll(oldString, newString);

所以这段代码可能有点难看,但它是有效的。我相信你可以清理它,但它完成了工作只要创建一个新文件并复制粘贴它(如果你愿意),如果你找不到更好的算法,请告诉我,我很乐意提供帮助:

public class contract {

  public contract(){

  }
  public static String replaceContractNo(String pMessage, String pInput, String pOutput) {

      return pMessage.replaceAll(pInput, pOutput);
    }

    public static void main(String args[]){

      contract myContract = new contract();

      String message = "hi John. You have two contracts listed: TV-70002548 and FV-50006578. The first contract ends on March 15th. I will pay you a final amount of 350 $.";

      int start1 = message.indexOf("TV");
      System.out.println(start1);
      int end1 = message.indexOf(' ', start1);
      System.out.println(end1);
      String str1 = message.substring(start1, end1);
      System.out.println(str1);

      String test1 = replaceContractNo(str1, "0", "null");
      System.out.println("test1 = "+test1);

      int start2 = message.indexOf("FV");
      int end2 = message.indexOf(' ', start2);
      String str2 = message.substring(start2, end2);

      String test2 = replaceContractNo(str2, "5", "five");
      System.out.println("test2 = " +test2);

      message = message.replaceAll(str1, test1);
      message = message.replaceAll(str2, test2);

      System.out.println(message);

        }

    }

嗨,没错!policyNumber是全局变量吗?另外,我看不出在这个函数中您在哪里使用contractno?我的意思是contractno在函数的范围内发生了更改,但它真正的用途是什么?对不起,这是一个拼写错误。我看应该是合同。你能告诉我你想要制作的字符串是什么样子的吗?如果有TV-70002548或FV-50006578或任何其他合同号,我想存储编号70002548和50006578,并将它们重写为七空二五四八等。嗨,非常感谢。我已经找到了一个类似于你的解决方案。但是谢谢分享!