Sivanesh selvaraj
Sivanesh selvaraj

Reputation: 23

Regex combination

Is it possible in regex to combine two validations? Whenever a series of 8 digit numbers(12345678) are given in a statement along with space(1234 5678) Regex should throw an error. Along with validation for alphabets &other special character .

Eg: 1234 apartment ,#23building state 234 456 (valid one)

1234 apartment ,#23building state 1234 5678 overhill (invalid one because of series/continuous of 8 digits)

677 flat, @(23) floor, up state 56789123 state UK ( invalid because of continuous 8 digits)

Upvotes: 0

Views: 218

Answers (1)

ctwheels
ctwheels

Reputation: 22817

Code

See regex in use here

(?:\d *){8}

Usage

See code in use here

import java.util.regex.Matcher;
import java.util.regex.Pattern;

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        final String regex = "(?:\\d *){8}";
        final String[] strings = {
            "1234 offshore address1234 Some locations",
            "1234 5678 offshore some location"
        };

        final Pattern pattern = Pattern.compile(regex);

        for (String s: strings) {
            Matcher matcher = pattern.matcher(s);
            if(!matcher.find()) {
                System.out.println(s);
            }
        }
    }
}

Results

Input

1234 offshore address1234 Some locations
1234 5678 offshore some location

Output

Below shows strings that don't match.

1234 offshore address1234 Some locations

Explanation

(?:\d *){8} matches a digit followed by any number of spaces exactly 8 times

Upvotes: 1

Related Questions