Home > Back-end >  Need to prevent 10 consecutive digits, and 11 consecutive digits, with some tricky parameters
Need to prevent 10 consecutive digits, and 11 consecutive digits, with some tricky parameters

Time:05-21

I'm trying to alter a regex expression for emails, with the requirement that we can't have a 10 digit phone number in it, or an 11 digit phone number that starts with a 1. The difficult part is that if the 11 digit phone number doesn't start with a 1, it's valid, and if it's more than 11 digits, it's valid. I'm getting hung up on the exactly 10 or 11 consecutive digits that doesn't also reject anything that's longer.

Here's my scenarios, my desired outcome, and my current outcome.

So right now my expression is succussfully rejecting things that have 10 consecutive digits, it also rejects anything longer than 10 digits, and so my 11 digit scenarios haven't mattered yet.

(?!^([0-9] *){10}).*^[_A-Za-z0-9-\ ] (\.[A-Za-z0-9-] )*@[_A-Za-z0-9-] (\.[A-Za-z0-9-] )*(\.[A-Za-z]{2,})$

There's a possibilty that this might just be too clever and specific for regex, and I could possibly break it out into more traditional java, but the area I'm working in would make it hard for that to specifically happen, so this is my first hopeful solution. Any help would be greatly appreciated.

CodePudding user response:

You may use this regex:

^(?!1?\d{10}@)[\w-] (?:\.[\w-] )*@[\w-] (?:\.[\w-] )*\.[A-Za-z]{2,}$

RegEx Demo

RegEx Details:

  • ^: Start
  • (?!1?\d{10}@): Negative lookahead to assert failure if we have 10 digits before @ or 1 followed by 10 digits before @
  • [\w-] : Match 1 of word or hyphen characters
  • (?:\.[\w-] )*: Match dot followed by 1 of word/hyphen characters. Repeat this group 0 or more times
  • @: Match a @
  • [\w-] : Match 1 of word or hyphen characters
  • (?:\.[\w-] )*: Match dot followed by 1 of word/hyphen characters. Repeat this group 0 or more times
  • \.[A-Za-z]{2,}: Match dot followed by 2 of English letters
  • $: End

CodePudding user response:

If you email addresses are already considered valid outside of your specific requirements, why not just reverse the validation?

  • just check to see if it starts with 10 digits or 1 followed by 10 and if so, reject it.
String[] data = { "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]" };

String regex = "^(1?\\d{10}@.*)";
        
for (String str : data) {
    System.out.println(str   " -> "
              (str.matches(regex) ? "fail" : "pass"));
}  

prints

[email protected] -> pass
[email protected] -> fail
[email protected] -> fail
[email protected] -> pass
[email protected] -> pass
  • Related