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 Handle, the duty is to get the extract port variety of the service.


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

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

Method: The issue could 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 components if they’re digits.

Observe the beneath steps to implement the thought:

  • 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 perform to search out.

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


import java.io.*;

import java.util.regex.Matcher;

import java.util.regex.Sample;


public class GFG {



    public static void essential(String[] args)





        String str = "http:/"

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

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


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






    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()) {


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






Given String is:
Above Given API is working on Port Quantity:

Associated Articles: