Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegExr with minimum 2 letter and optional letters, but no other letters?

Tags:

regex

php

I want a regex for an text, that allow it, if atleast 1 word with 2 letters are inside, and minimum 25 letters or digits and also allow (0-9äöü,.' -), if other letters or digits there, it should be give an error.


Example:

correct:

  • John Doe
  • Max Müstermann
  • John-Frank' Doe.

false:

  • John/Doe

Regex:

  • Wordregex: ([a-z]{2})\w+
  • allowed Items: [äöü0-9,.' -]
  • max length: {25,999}
if(preg_match("/([A-Za-z]{2})\w+/",$text)){
    if(!preg_match("/[a-zäöüA-ZÄÖÜ,.' -]/g",$text)){echo 'error';}
else{echo'error';}

I'm not sure how to get the solution in code.

like image 418
klediooo Avatar asked Jul 05 '19 19:07

klediooo


People also ask

How do I get only letters in regex?

How do you match letters in regex? To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" .

What does \\ mean in regex?

The backslash character (\) in a regular expression indicates that the character that follows it either is a special character (as shown in the following table), or should be interpreted literally. For more information, see Character Escapes. Escaped character. Description. Pattern.

How do you not allow characters in regex?

To represent this, we use a similar expression that excludes specific characters using the square brackets and the ^ (hat). For example, the pattern [^abc] will match any single character except for the letters a, b, or c.


1 Answers

What you might do is use a positive lookahead to assert the length of 25 - 999 and also assert that there are 2 consecutive [a-z]

Then match your character class [a-zA-Z0-9äöü,.' -]+ with the allowed items adding a-z and A-Z to it.

^(?=.{25,999})(?=.*[a-z]{2})[a-zA-Z0-9äöü,.' -]+$
  • ^ Start of string
  • (?=.{25,999}) Positive lookahead, assert 25 - 99 characters
  • (?=.*[a-z]{2}) Positive lookahead, assert 2 times [a-z]
  • [a-zA-Z0-9äöü,.' -]+ Match any of the listed 1+ times
  • $ End of string

Regex demo | Php demo

For example (I have made the strings longer to account for the minimum length of 25)

$strings = [
    "This is a text with John Doe",
    "This is a text with Max Müstermann ",
    "This is a text withJohn-Frank' Doe.",
    "This is a text with John/Doejlkjkjlk",
];
$pattern = "/^(?=.{25,999})(?=.*[a-z]{2})[a-zA-Z0-9äöü,.' -]+$/";
foreach ($strings as $string) {
    if (preg_match($pattern, $string)) {
        echo "Ok ==> $string" . PHP_EOL;
    } else {
        echo "error" . PHP_EOL;
    }
}

Result

Ok ==> This is a text with John Doe
Ok ==> This is a text with Max Müstermann 
Ok ==> This is a text withJohn-Frank' Doe.
error
like image 124
The fourth bird Avatar answered Sep 19 '22 01:09

The fourth bird