pikapika pikapika - 2 years ago 100
Python Question

Perl regular expression \U

I am trying to convert some perl code to python. I came across this line

if($Var=~ /^\U/)
{ dosomething(); }

I have looked over the web for expression, but i am not able to comprehend its meaning.

\U uppercase till \E

\E end case modification

Please give an example of the correct usage if possible and how to approach for a python equivalent.

Answer Source

The regex engine knows nothing of \U. It's processed by the Perl parser in double quoted and regex literals.

"\Uabcdef"       is the same as     uc("abcdef")
"\Uabc\Edef"     is the same as     uc("abc")."def"

That means that

/^\Uabc/         is the same as     /^ABC/
/^\U/            is the same as     /^/

/^/ (and thus /^\U/) is rather pointless, as it will always match.

If you wanted to make sure a string consists entirely of upper case letters, you'd use /^\p{Lu}*\z/, or /^[A-Z]*\z/ if you have a very limited definition of letter.


$var =~ /\Uabc\Edef/

would be written as follows in Python:

re.search("abc".upper() + "def", var)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download