Tuesday, March 21, 2023
HomeSoftware DevelopmentExtracting Port Quantity from a localhost API Request to a Server utilizing...

Extracting Port Quantity from a localhost API Request to a Server utilizing Common Expressions


Enhance Article

Save Article

Like Article

Enhance Article

Save Article

Given a String test_str as localhost API Request Deal with, the duty is to get the extract port variety of the service.

Examples:

Enter: test_str = ‘http://localhost:8109/customers/addUsers’
Output: 8109
Clarification: Port Quantity, 8109 extracted.

Enter: test_str = ‘http://localhost:1337/api/merchandise’
Output: 1337
Clarification: Port Quantity, 1337 extracted.

Strategy: The issue might be solved based mostly on the next concept:

Create a regex sample to validate the quantity as written beneath:   
regex = “[:]{1}[0-9]{4, }“

The place,  

  • [:]: This sample will match if one of many previous is a colon character
  • [0-9]{4} : This sample will enable 4 or greater than 4 previous parts if they’re digits.

Comply with the beneath steps to implement the concept:

  • Create a regex expression to extract all of the Port numbers from the string.
  • Use Sample class to compile the regex fashioned.
  • Use the matcher operate to seek out.

Beneath is the code implementation of the above-discussed method:

Java

import java.io.*;

import java.util.regex.Matcher;

import java.util.regex.Sample;

  

public class GFG {

  

    

    public static void foremost(String[] args)

    {

  

        

        

        String str = "http:/"

                     + "/localhost:8082/api/safe";

        System.out.println("Given String is:n" + str);

        System.out.println(

            "Above Given API is operating on Port Quantity:");

        extractPortNumber(str);

    }

  

    

    

    static void extractPortNumber(String str)

    {

  

        

        

        

        

        String strPattern[] = { "[:]{1}[0-9]{4}" };

        for (int i = 0; i < strPattern.size; i++) {

            Sample sample

                = Sample.compile(strPattern[i]);

            Matcher matcher = sample.matcher(str);

            whereas (matcher.discover()) {

                System.out.println(

                    matcher.group().change(":", ""));

            }

        }

    }

}

Output

Given String is:
http://localhost:8082/api/safe
Above Given API is operating on Port Quantity:
8082

Associated Articles:

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

When Carriers Collaborate

Recent Comments