Search code examples
javaregex

How to use regex in Java for complex strings


I am new to JAVA coding, and I am trying to learn how to use regex.

The input string:

String URL = "{Records=[{messageId=ac013823-100a-4b92-bb7a-a891b7b113d1, "
                + "receiptHandle=AQEBtDp6D3AVkifVlrM/No2dtCxxazqQOGjFcNrUO2t0JLS0awsBMEEwPfbdwrLyrO8ovneeAs3LIr30kPsx/T7NDP3mAOnYfPAMswHf4hQxQS2H7XCFc5ii/fCNai9FdaV+I/281MCHswfWYhoQII6e+alGmkPuwXPjBvQG6PDsFh9OF+/B05MBYP2uGR4mPoBfAJinDbabyZ7QaTEkgeATgvrHB7OmF0AJaJi/cN8bioZ2W+54bTi5HOJPF/oyCScGOYdTjtSDtvc1L+GP3qm2cC2m5XQ05ziCF3S7LUhjN6Go9EGkn1K1BLQPI/EbkIr8fGOzCmvl3NzE222pAArn2UxNCztSAerkpSfPTVAM72AOygXYXVWosmRMo4E7uT0H, body={\r\n"
                + "  \"tenant\": \"https://example.com,us-east-1-oe-stg-001-lc000chart,us-east-1\"\r\n"
                + "}, attributes={ApproximateReceiveCount=455, "
                + "SentTimestamp=1722503530891, SenderId=AIDAQKVRD5OEBZLPV7XNP, "
                + "ApproximateFirstReceiveTimestamp=1722503535891}, messageAttributes={}, "
                + "md5OfBody=5a8e4022b9b9876a4c854e2a02d4c3b9, eventSource=aws:sqs, eventSourceARN=arn:aws:sqs:us-east-1:022920031112:teq, "
                + "awsRegion=us-east-1}]}";

Now what I need is, entire line after the "tenant" string untill "us-east-1".

So basically this line:

"tenant\": \"https://example.com,us-east-1-oe-stg-001-lc000chart,us-east-1

So I wrote the regex like this:

 Pattern pattern = Pattern.compile("[^tenant]+[0-9a-zA-Z]+(,[0-9a-zA-Z]+)*$");
        Matcher matcher = pattern.matcher(URL);
        if (matcher.find()) {
            System.out.println(matcher.group(0)); // prints /{item}/
        } else {
            System.out.println("Match not found");
        }

But it is not working, not sure why. What am I doing wrong here?


Solution

  • It is better to deserialize string to JSON and get attribute. For example with jackson library. But you should generate valid json string, current string is not valid json string

    ObjectMapper objectMapper = new ObjectMapper();
    JsonNode jsonNode = objectMapper.readTree(jsonString);
    JsonNode tenant= jsonNode.get("body").get("tenant");
    

    I dont recommend you to use regexp for this task, but here is an example of regexp you want

     String regex = "\"tenant\": \"([^\"]+)\"";
     Pattern pattern = Pattern.compile(regex);
     Matcher matcher = pattern.matcher(input);
    
     if (matcher.find()) {
         String tenantValue = matcher.group(1);
         System.out.println("Tenant value: " + tenantValue);
     }