0

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.

ThatGuy343
  • 2,354
  • 3
  • 30
  • 55

4 Answers4

1

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...

John
  • 916
  • 7
  • 14
1
/((((\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

İlker Korkut
  • 3,129
  • 3
  • 30
  • 51
0

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}

afzalex
  • 8,598
  • 2
  • 34
  • 61
0

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();
    }
}
sol4me
  • 15,233
  • 5
  • 34
  • 34