Java字符串与html标记的比较

时间:2012-09-07 10:56:48

标签: java

我有两个字符串如下:

String input="<tr><td>Hello world</td></tr>";
String output="<body><tr><td>Hello world</td></tr></body>";

我想比较两个字符串,如果输入字符串不包含<body></body>标记,则需要从输出字符串中删除<body>标记。字符串可以是任意长度。

如何根据输入字符串比较和替换输出字符串? <body>标记可能类似于<body ></body > or < body>< /body>,etc

需要找到标签并根据输入字符串替换它。

4 个答案:

答案 0 :(得分:1)

static String[] combinations = new String[] {
    "<body>","</body>","< body>","< /body>","<body >"
};

for (int i = 0; i < combinations.length; i++) {
    if (!input.contains(combinations[i])) {  
        output = output.replace(combinations[i], "");    
    }    
}

答案 1 :(得分:1)

 String resultingOutput = "";
 if( !(input.contains("<body>")) && !(input.contains("</body>")) ){
      resultingOutput = output.replace("<body>", "").replace("</body>","");
 }

答案 2 :(得分:-1)

int compare;
if (!input.contains("<body>"))
compare = output.replaceAll("<body>","").replaceAll("</body>","").compareTo(input);

答案 3 :(得分:-1)

public class Practice {

public static void main(String[] args) {
    String input = "<tr><td>Hello world</td></tr>";
    String output = "<body><tr><td>Hello world</td></tr></body>";
    String tag = "<body>";
    String replace = "";

    System.out.println("Output : " + validate(input, output, tag, replace));

}

private static String validate(String input, String output, String word,
        String replace) {

    if (!(input.contains(word)) && !(input.contains(word))) {
        output = output.replace(word, replace).replace(word, replace);
    }
    return output;

}}