editing dynamic string // substring for dynamic xml value

edited November 2015 in How To...

Hello, I working on a project when I load a value from online xml table ( it's time, for example 12:45 PM) and I need the value to convert, I'd like to have just 1245. Something like substring but for dynamic value. I need to work with this number afterwards, so it was a whole number without letters or anything. Thanks for all your suggestions!!

Tagged:

Answers

  • yee so the value is online on the url, i just know the value is 12:45 pm and I need clear number like 1245. Please help with that.

  • There are different methods to extact parts of a string. Here are three different approaches:

    import java.util.regex.*;
    String original = "12:45 PM";
    
    void setup() {
      // pick the substrings directly
      println(original.substring(0, 2) + original.substring(3,5) );
    
      // split the whole string into parts, seperated by spaces
      String[] parts = split(original, " ");
      // remove the colon
      println(parts[0].replace(":", ""));
    
      // use a regular expression to get the desired part
      Pattern p = Pattern.compile("(\\d\\d):(\\d\\d)");
      Matcher m = p.matcher(original);
      if(m.find()){
        println(m.group(1)+m.group(2));
      }
    
    }
    
  • edited November 2015

    This would work, but there is problem that is loaded from XML which is placed on the interned so the String is in the document described as

    String zip = "10003";
    String url = "http://"  + "xml.weather.yahoo.com/forecastrss?p=" + zip;    
    String time = "";  // dynamic value 12:45
    time = forecas.getString("time");
    XML forecast = xml.getChild("channel/item/yweather:forecast"); // in this parent is placed child called "time"
    

    but thanks for this solution benja! I am saving it for the next time

  • @honzojd: As with your other post: include a sample of the XML. If the time is in a standard datetime format you should be able to parse it directly to a date object, which is probably your intention...

    @benja: if the intention is to do something programmatically with the time values then none of your suggestions are especially useful as you're simply swapping one string representation for another. @GoToLoop's suggestion is better, but a datetime parser may be the best option depending on the string being parsed...

  • @blindfish: I've updated the comment "sorry for the HTML in the middle". Btw: good wise answer, thank you for this comment. Yes that's my intention but I don't know how to do it when I am not able to edit the XML and substrings didn't work :/

Sign In or Register to comment.