在Java中查找和删除子字符串

时间:2014-05-07 00:46:30

标签: java string

我正在尝试查找Java子字符串,然后将其删除而不删除字符串的其余部分。

我将XML作为输入,并希望删除已弃用的标记,例如:

public class whatever {
    public static void main(String[] args) {

    String uploadedXML = "<someStuff>Bats!</someStuff> <name></name>";
    CharSequence deleteRaise = "<name>";

    // If an Addenda exists we continue with the process    
    if (xml_in.contains(deleteRaise)){
        // delete
    } else {
        // Carry on
    }
}

在那里,我想删除<name></name>标记(如果它们包含在字符串中),同时离开<someStuff></someStuff>

我已经将XML解析为String,所以没有问题。我需要知道如何找到特定字符串并删除它们。

2 个答案:

答案 0 :(得分:3)

您可以使用replaceAll(regex, str)执行此操作。如果您不熟悉正则表达式,则?仅表示字符串中0 or 1出现/次,因此它涵盖<name>和{{1} }}

</name>

String uploadedXML = "<someStuff>Bats!</someStuff> <name></name>";
String filter = "</?name>";
uploadedXML = uploadedXML.replaceAll(filter, "");

System.out.println(uploadedXML);

答案 1 :(得分:1)

String uploadedXML = "<someStuff>Bats!</someStuff> <name></name>";
String deleteRaise = "<name>";
String closeName = "</name>"
// If an Addenda exists we continue with the process    
if (xml_in.contains(deleteRaise)){
    uploadedXML.replace(uploadedXML.substring(uploadedXML.indexOf(deleteRaise),uploadedXML.indexOf(closeName)+1),"");
} else {
    // Carry on
}enter code here