This can’t be done out of the box, you need to use the gform_field_validation filter to run your own custom PHP validation function, here’s the documentation for the filter: https://docs.gravityforms.com/gform_field_validation/
That code isn’t going to work for a few reasons, most notably because of the undefined variables ($word and $str) you’re using. You need to be comparing your regex pattern against the field value (available in $value).
I’d do something like the following to compare the field value against a regex pattern that will only allow A-Z characters and throw an error if any numbers, spaces, or special characters are present in the value:
In regards to the overall issue at hand, it is almost always a better user experience to allow the user to enter values into fields in whatever format they desire and just fix it in the background to the format you want when the values are saved.
Obviously there are exceptions to this with more specifically formatted values like emails, usernames, passwords, etc. but if it’s just a string of text you need to collect on the form, it’s better to just convert it to the format you’d like it to be in for your records, rather than putting the burden on the user to adapt to that format. Keep in mind, with every validation error the user is presented with, they will be progressively more unlikely to correct that error and fully submit the form.
Adding an empty value check to the logic should be able to adjust for that and only compare fields that have an entered value against the regex pattern.