+ Reply to Thread
Results 1 to 2 of 2

Thread: Extract a certain value from string

  1. #1
    Junior Member
    Join Date
    May 2012
    Posts
    10

    Extract a certain value from string

    I have that string for example : "Name:John," + "Age: 35"
    I want to extract the Name value which will be John .
    Any ideas how can that be done ?

  2. #2
    Junior Member
    Join Date
    Jan 2012
    Posts
    36
    There are two ways to do it .
    1) The normal Loop way
    2) The Regex way.

    1) The normal way :
    Code:
    String[] couple = string.split(",");
    
     for(int i =0; i < couple.length ; i++) {
        String[] items =couple[i].split(":");
        items[0]; //Key
        items[1]; //Value
    }
    2) The Regex way :
    Code:
        String string = "Name:armand,Age:22,";
        Pattern pattern = Pattern.compile("(\\w+?):(\\w+?),");
        Matcher matcher = pattern.matcher(string);
        while (matcher.find()) {
            String key = matcher.group(1);
            String value = matcher.group(2);
    
            System.out.println("Key : " + key + " value : " + value);
        }

+ Reply to Thread

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts