How to remove all String text before equals ('=') sign Java

前端 未结 4 908
自闭症患者
自闭症患者 2021-01-21 07:51

I\'d like to parse a string so I can build an XML document.

I have:

String value = \"path=/Some/Xpath/Here\";

I\'ve parsed it this way

相关标签:
4条回答
  • 2021-01-21 08:47

    Try with:

    private void parseXpath() {
        String s = "path=/Some/Xpath/Here";
        s = s.replace("path=","");
    
        String[] tokens = s.split("/");
        for(String t: tokens){
            System.out.println(t);
        }
    }
    

    Also you can avoid removing it at all, if you get path=/Some/Xpath/Here by other regex, use lookbehind instead of exact matching:

    (?<=path=)[^\\,]*
    

    you should get just /Some/Xpath/Here.

    EDIT If you want to print array as String, use static method Arrays.toString(yourArray);

    0 讨论(0)
  • 2021-01-21 08:50

    Although the question is tagged with regex here is a solution using substring

        String[] tokens = s.substring(s.indexOf("=") + 1).split("/");
    

    or

        String[] tokens = s.substring(s.indexOf("=/") + 1).split("/");
    
    0 讨论(0)
  • 2021-01-21 08:52

    if you are looking into performance you should avoid usage of split since it uses regular-expressions which is a bit oversized for such a simple problem. if you just want to remove "path=" and you are sure that your string always starts that way you could go with the following:

    String s = "path=/Some/Xpath/Here";
    String prefix = "path=";
    String result = s.substring(prefix.length);
    
    0 讨论(0)
  • 2021-01-21 08:54

    Just do replace before splitting.

    String[] tokens = s.replaceFirst(".*=", "").split("/");
    

    This would give you an empty element at first because it would do splitting on the first forward slash after replacing.

    or

    String[] tokens = s.replaceFirst(".*=/", "").split("/");
    

    But if you remove all the chars upto the = along with the first forward slash will give you the desired output.

    0 讨论(0)
提交回复
热议问题