ThatGuy343
ThatGuy343

Reputation: 2424

How to identify patterns of repeated characters within string?

Lets say you have a string like this:

198<string>12<string>88<string>201

Yes that looks like an IPv4 address, because it is one.

How do i check to see if there are repeated patterns in a string? I've no idea where to start, and im not sure that regex would help since i dont really know what string to look for, just that it will be repeated.

The goal here is to strip <string> from the main string.

Okay lets say the string is:

String test = "112(dot)115(dot)48(dot)582";
if(isIP(test){
   System.out.println("Yep, it's an ip");
}

The output should be:

Yep, it's an ip

The seperator (dot) will always be different.

Upvotes: 0

Views: 219

Answers (4)

sol4me
sol4me

Reputation: 15698

This should help

import java.util.regex.Pattern;

public class App
{
    private static String IPV4_REGEX ="^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$";
    private static final Pattern IP4_PATTERN = Pattern.compile(IPV4_REGEX);

    public static void main( String[] args ) {
        String test1 = "198<string>12<string>88<string>201";
        String test2 = "198(foo)12(foo)88(foo)201";
        if(isIP(test1)) {
            System.out.println("Yep, it's an ip");
        }
        if(isIP(test2)) {
            System.out.println("Yep, it's an ip");
        }
    }

    public static boolean isIP(String input) {

        String[] chunks = input.replaceAll("[^\\d.]", "x").split("x+");
        if (chunks.length != 4) {
            System.out.println("not valid ");
            return false; 
        }

        String ip = chunks[0] + "." + chunks[1] + "." + chunks[2] + "." + chunks[3];
        return IP4_PATTERN.matcher(ip).matches();
    }
}

Upvotes: 0

afzalex
afzalex

Reputation: 8652

You will need to capture group to accomplish this and use Non number D.

public boolean isIP(String test) {
    String regex = "\\d+(\\D+)\\d+\\1\\d+\\1\\d+";
    return test.matches(regex);
}

Here I have used regex : \d+(\D+)\d+\1\d+\1\d+ It is equivalent to : -

  \d+          (\D+)       \d+         \1          \d+          \1         \d+
numbers_1 non-numbers_1 numbers_2 non-numbers_1 numbers_3 non-numbers_1 numbers_4

Or you can further reduce the above regex to \d+(\D+)\d+(\1\d+){2}

Upvotes: 0

John
John

Reputation: 916

Try this: https://regex101.com/r/oR1gS8/4

/^((?:\d{1,3}[^0-9]+){3}\d{1,3})$/

Matches 198<string>12<string>88<string>201, 112(dot)115(dot)48(dot)582, and 112<test>115<test>48<test>582, among others...

Upvotes: 1

İlker Korkut
İlker Korkut

Reputation: 3250

/((((\d{1,3})\D{1,5}){3})(\d{1,3}))$/

112(dot)115(dot)48(dot)582

Matches

1.  [0-26]  `112(dot)115(dot)48(dot)582`
2.  [0-23]  `112(dot)115(dot)48(dot)`
3.  [16-23] `48(dot)`
4.  [16-18] `48`
5.  [23-26] `582`

control one by one your cases in here

Upvotes: 1

Related Questions