匹配String中的子字符串

时间:2016-02-16 09:46:40

标签: java regex string

我正在尝试在字符串中查找子字符串。然后从原始字符串&amp;中删除已存在的<b>标记。在&amp;之前添加<b>标记在原始字符串中存在子字符串之后。

我需要帮助,到目前为止我已经尝试过了

String originalString = "<b>ProLiantDL380CltrG2</b> HWSupp";
String subString = "ProLia"

if (StringUtils.containsIgnoreCase(originalString, subString)) {

System.out.println("substring matched true");
System.out.println("before : " + originalString);
//Need to remove the <b> & </b> from the originalString
originalString.replace("<b>", ""); // doesn't work
originalString.replace("</b>", "");
System.out.println("after : " + originalString);
//after remove the <b> tags I need to add those tags at the start &
end index of the substring existence in the original string
like "<b>ProLia</b>ntDL380CltrG2 HWSupp"
   }
}

输出:不如预期

product matched true
before :  <b>ProLiantDL380CltrG2</b> HWSupp
after :  <b>ProLiantDL380CltrG2</b> HWSupp

2 个答案:

答案 0 :(得分:2)

在Java中,字符串是不可变的。你需要在修改它时取回字符串

originalString.replace("<b>", "");
originalString.replace("</b>", "");

这意味着您只是修改字符串而不是将其分配给原始字符串。

因此你的代码应该是

originalString= originalString.replace("<b>", "");
originalString= originalString.replace("</b>", "");

为了获得索引,您应该使用indexOf(),它为您提供起始索引,并为其添加子字符串长度,为您提供结束索引。

答案 1 :(得分:1)

你应该使用stringBuilder来执行这些条件,这是最快的方法,请尝试以下代码,

import com.sun.org.apache.xml.internal.utils.StringComparable;
import com.sun.xml.internal.ws.util.StringUtils;

public class matchSubstring {

    public static void main (String[]args){

    String originalString = "<b>ProLiantDL380CltrG2</b> HWSupp";
    String subString = "ProLia";

    if (originalString.contains(subString)) {
    System.out.println("substring matched true");
    System.out.println("before : " + originalString);
    //Need to remove the <b> & </b> from the originalString
    originalString= originalString.replace("<b>", ""); 
    originalString=originalString.replace("</b>", "");

    StringBuilder strb=new StringBuilder(originalString).insert(subString.length(),"</b>");
    strb.insert(0,"<b>");

    System.out.println("after : " + strb);
}
}}

<强>输出:

substring matched true
before : <b>ProLiantDL380CltrG2</b> HWSupp
after concat: <b>ProLia</b>ntDL380CltrG2 HWSupp