尝试替换某些字符串时,Java代码会无限循环

时间:2014-04-18 08:25:25

标签: java regex loops

以下代码替换了%%。

之间字符串的出现次数
String OrgStr = "Alarm for %Received Number% has arrived %test% is ok. Please visit %Received Number%";
String rcNumber = "1234567";

int firstPer, secPer;
do
{
    firstPer = OrgStr.indexOf('%'); //position of first %
    secPer = OrgStr.indexOf('%', firstPer+1); //position of second %

    //extract the string in between first % and second %
    String toBeReplac = OrgStr.substring(firstPer, secPer+1);

    //The replaced string
    //if (toBeReplac.equals("%Received Number%"))// if i put this if condition then code goes to infinite loop
        OrgStr=OrgStr.substring(0, firstPer)+ rcNumber +OrgStr.substring((secPer+1),OrgStr.length());

    firstPer = OrgStr.indexOf('%', firstPer+1);
}while(firstPer>0);

System.out.println(OrgStr);

正如我在上面的代码中提到的那样,当我放入行if (toBeReplac.equals("%Received Number%"))时,代码进入无限循环。我想只在%之间的字符串是Received Number时才进行替换。

3 个答案:

答案 0 :(得分:0)

试试这个:

      String Str = "Alarm for %Received Number% has arrived %test% is ok. Please visit %Received Number%";
      System.out.println(Str.replaceAll("%Received Number%","Java"));

OutPut:

         Alarm for AMROOD has arrived %test% is ok. Please visit AMROOD

答案 1 :(得分:0)

基本上问题是你在每次迭代时重新初始化 firstPer 的值:

firstPer = OrgStr.indexOf('%');

firstPer 始终具有第一次出现'%'的值,这就是您有无限循环的原因。

因此,您需要为该调用添加第二个参数,以确保 firstPer 的值更新或在其他地方初始化 firstPer ,只需更新一次正确的价值。

修改

澄清一下,你只需要剪切句子

firstPer = OrgStr.indexOf('%');

并在执行之前粘贴它。然后,您将获得以下输出:

  

1234567的警报已到达%test%即可。请访问1234567

我猜这是你正在寻找的输出。

答案 2 :(得分:0)

正确的代码可以:

firstPer = OrgStr.indexOf('%'); //position of first %
secPer = OrgStr.indexOf('%', firstPer+1); //position of second %
if (firstPer == -1 || secPer == 0) {
    break;
}

(或者将条件反转并将其余部分放在if中。)

最好使用StringBuffer更高效的模式替换

public String eval(String s) {
    StringBuffer sb = new StringBuffer();
    Pattern variablePattern = Pattern.compile("%([\\w ]{0,20})%");
    Matcher matcher = variablePattern.matcher(s);
    while (matcher.find()) {
        String variable = matcher.group(1);
        String value = matcher.group(0);
        switch (variable) {
            case "":
                value = "%"; // "%%" becomes a single "%" (self-escaped.
                break;
            case "Received Number":
                value = "123456";
                break;
            case "test":
                value = "...";
                break;
            default:
                throw new IllegalArgumentException("No such variable: " + variable);
        }
        matcher.appendReplacement(sb, value);
    }
    matcher.appendTail(sb);
    return sb.toString();
}

这里我认为变量名只包含单词字符或空格,最多20个字符。这应该有助于文本中的唯一百分比。并且可以通过变量“%%”来实现百分比。

如果在地图名称到值中维护变量,则不需要switch语句

public String eval(String s, Map<String, String> variables) {

}