Hatefiend
Hatefiend

Reputation: 3596

Algorithm for IP Address-like String extraction? [Java]

Given a strings like:

S5.4.2

3.2

SD45.G.94L5456.294.1004.8888.0.23QWZZZZ

5.44444444444444444444444444444.5GXV

You would need to return:

5.4.2

3.2

5456.294.1004.8888.0.23

5.44444444444444444444444444444.5

Is there a smart way to write a method to extract only the IP address-like number from it? (I say IP Address-like because I'm not sure if IP addresses are usually a set amount of numbers or not). One of my friends suggested that there might be a regex for what I'm looking for and so I found this. The problem with that solution is I think it is limited to only 4 integers total, and also won't expect ints like with 4+ digits in between dots.

I would need it to recognize the pattern:

NUMS DOT (only one) NUMS DOT (only one) NUMS

Meaning:

234..54.89 FAIL

.54.6.10 FAIL

256 FAIL

234.7885.924.120.2.0.4 PASS

Any ideas? Thanks everyone. I've been at this for a few hours and can't figure this out.

Upvotes: 1

Views: 430

Answers (2)

user4398985
user4398985

Reputation:

There are many ways to do it. This is the best way, I guess.

public static String NonDigits(final CharSequence input)
{
final StringBuilder sb = new StringBuilder(input.length());
for(int i = 0; i < input.length(); i++){
    final char c = input.charAt(i);
    if(c > 47 && c < 58){
        sb.append(c);
    }
}
return sb.toString();
}

A CharSequence is a readable sequence of characters. This interface provides uniform, read-only access to many different kinds of character sequences.

  1. Look at this ASCII Table. The ascii values from 47 to 58 are 0 to 9. So, this is the best possible way to extract the digits than any other way.

  2. "final" keyword is more like if set once, cannot be modified. Declaring string as final is good practise.

Same code, just to understand the code in a better way:

public static String NonDigits(String input)
{
    StringBuilder sb = new StringBuilder(input.length());

    for(int i = 0; i < input.length(); i++)
    {
        char c = input.charAt(i);
        if(c > 47 && c < 58)
        {
            sb.append(c);
        }
}
return sb.toString();
}

Upvotes: 1

shofstetter
shofstetter

Reputation: 254

Here is an approach using Regex:

    private static String getNumbers(String toTest){
        String IPADDRESS_PATTERN =
                "(\\d+\\.)+\\d+";

        Pattern pattern = Pattern.compile(IPADDRESS_PATTERN);
        Matcher matcher = pattern.matcher(toTest);
        if (matcher.find()) {
            return matcher.group();
        }
        else{
            return "did not match anything..";
        }
    }

This will match the number-dot-number-... pattern with an infinite amount of numbers.

I modified this Answer a bit.

Upvotes: 2

Related Questions