javasmsat-commandstring-parsingmodem

Get the biginteger number from String in java


I'm trying to parse messages I receive using AT+CMGL command.

My main interest is to get the 15 digit number from the message and store it in a table.

Here's an example of the data the I receive :

+CMGL: 0,"REC READ","+212664090320",,"22/09/14,10:58:33+04"
876011033120958
+CMGL: 0,"REC READ","+212664486654",,"22/09/14,11:47:33+04"
Ver:03.27.07_00 GPS:AXN_5.1.9 Hw:FMB920 Mod:13 IMEI:350444465129844 Init:2022-9-6 12:0 Uptime:1193 MAC:380A2986D9CB SPC:1(0) AXL:0 OBD:0 BL:1.10 BT:4

fyi, i get 8 different message format, I've just listed two here.


Solution

    1. Number storage mechanisms are for numbers, i.e. things you intend to do math on. It makes no sense to add 1 from an IMEI, or to subtract one IMEI from another. I doubt it's particularly sensible, therefore, to use BigInteger as storage format for an IMEI. String is fine.

    2. To extract the IMEI from such input, regular expressions seem useful. I'd try \bIMEI:(\d{15,16})\b. That means: A 'word break', then IMEI:, then either 15 or 16 digits, then another word break. (IMEI are 15 or 16 digits currently). You can future proof matters by just using \\d+, which means '1 or more digits'. The parentheses also allow us to get that number out later. Then, make a matcher, find(), and ask for group(1):

    private static final Pattern IMEI_FINDER = Pattern.compile("\\bIMEI:(\\d{15,16})\\b");
    
    public String extractImei(String in) {
      Matcher m = IMEI_FINDER.matcher(in);
      if (m.find()) return m.group(1);
      throw new IllegalArgumentException("No IMEI found: " + in);
    }
    

    The above will return the first IMEI found in the input. You can repeatedly call find() if there are multiple IMEI: entries in there and you want them all; something like:

    while (m.find()) imeiList.add(m.group(1));