-4

The input is a string : {"Id":"490145","Index":null,"Type":"BOOK"}

How do I extract the number 490145 from the above string? All those : and " confuse me.

Edit 1: The question of the post is not "how to decode json using existing library" but how to specifically use Regular Expression to solve the problem.

Edit 2: Another question: How do I extract "BOOK" from the string?

StackJay
  • 61
  • 1
  • 9

1 Answers1

0

Regular expressions in java can be easily handled by the java.util.regex package. You can also find the regular expression sintax in Regular expression documentation

Besides, in this tutorial you will find an example to use this package wich basically uses two classes: java.util.regex.Matcher and java.util.regex.Pattern;

One possible solution to your question would be:

    import java.util.regex.Matcher;
    import java.util.regex.Pattern;

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

        // String to be scanned to find the pattern.
        String line="{\"Id\":\"490145\",\"Index\":null,\"Type\":\"BOOK\"}";
        String pattern = "(\\d+)";

        // Create a Pattern object
        Pattern r = Pattern.compile(pattern);

        // Now create matcher object.
        Matcher m = r.matcher(line);
        if (m.find( )) {
            System.out.println("Found value: " + m.group(0) );
        } else {
            System.out.println("NO MATCH");
        }
    }
    }

Instead, if you want to obtain the value of each field (Id, Index and Type), the pattern should consist of 6 groups (I assumed the Index composed of characters and not numbers):

String pattern = "(\"Id\":\")(\\d+)(\",\"Index\":)(\\w+)(,\"Type\":\")(\\w+)";

While the outputs would be:

System.out.println("Found value for Id: " + m.group(2) );
System.out.println("Found value for Index: " + m.group(4) );
System.out.println("Found value for Type: " + m.group(6) );
EloyRoura
  • 24
  • 5
  • Thanks for the help Eloy! Another question is, how do I extract "BOOK" from the string? – StackJay Jan 12 '16 at 01:42
  • I am not sure if that's what you are looking for, but my understanding is that you are looking for the three main fields (Id, Index and Type). Thue, what follows is the pattern: String pattern = "(\"Id\":\")(\\d+)(\",\"Index\":)(\\w+)(,\"Type\":\")(\\w+)(\")"; and here the code for the outputs: System.out.println("Found value for Id: " + m.group(2) ); System.out.println("Found value for Index: " + m.group(4) ); System.out.println("Found value for Type: " + m.group(6) ); – EloyRoura Jan 12 '16 at 02:24
  • That solves my problem completely. Thanks so much! – StackJay Jan 12 '16 at 02:29