Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match ALL-CAPS words of a certain length

Tags:

regex

php

I have a function which fixes capitalization for those naughty users that insist on making everything UPPERCASE!

I want my function to only be called when a string contains an uppercase word of 3 or more uppercase letters.

Can this be done with a regex?

examples: for example: I = false, DEAL = true, Welcome = false

like image 807
Haroldo Avatar asked Nov 23 '10 10:11

Haroldo


People also ask

How do you match a capital letter in regex?

Using character sets For example, the regular expression "[ A-Za-z] " specifies to match any single uppercase or lowercase letter. In the character set, a hyphen indicates a range of characters, for example [A-Z] will match any one capital letter. In a character set a ^ character negates the following characters.

What does regular expression a to z match?

The regular expression [A-Z][a-z]* matches any sequence of letters that starts with an uppercase letter and is followed by zero or more lowercase letters.

What is b regex?

The word boundary \b matches positions where one side is a word character (usually a letter, digit or underscore—but see below for variations across engines) and the other side is not a word character (for instance, it may be the beginning of the string or a space character).

How do you denote special characters in regex?

Special Regex Characters: These characters have special meaning in regex (to be discussed below): . , + , * , ? , ^ , $ , ( , ) , [ , ] , { , } , | , \ . Escape Sequences (\char): To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "."


1 Answers

if (preg_match('/\b\p{L}*\p{Lu}{3}\p{L}*\b/u', $str)) {
    // Naughty user!
}

will match any word that contains at least three uppercase letters. It doesn't matter whether the word starts with an uppercase or lowercase letter, so it would match, for example iTUNES or StackOVERflow as complete words.

If you want to restrict yourself to words that consist entirely of uppercase characters, three or more, then use

if (preg_match('/\b\p{Lu}{3,}\b/u', $str)) {
    // Naughty user!
}
like image 195
Tim Pietzcker Avatar answered Oct 21 '22 03:10

Tim Pietzcker