0

My below code doesn't return true in result:

String NameRegex = '/^[A-z]+$/';
Pattern MyPattern = Pattern.compile(NameRegex);
Matcher MyMatcher = MyPattern.matcher('TEST');
Boolean result = MyMatcher.matches();

result will throw always false. What the problem?

  • Documentation says: "A pattern is a compiled representation of a regular expression. Patterns are used by matchers to perform match operations on a character string.", so it is not a reg exp itself. - developer.salesforce.com/docs/atlas.en-us.apexcode.meta/…. Try to use [A-z]+, that will work – kurunve Mar 1 '18 at 7:56
  • 1
    @kurunve A pattern is a compiled regex. – sfdcfox Mar 1 '18 at 7:59
2

Apex Regex isn't like JavaScript's regex. You don't start/end with / characters unless you're trying to match them. For example, given your code, the string /hello/ would match. Also, A-z is not correct, because it would match all characters between A and z, which, if you look at a character map, includes some punctuation as well ([\]^_ characters). You need to match A-Za-z, because regex is case sensitive.

String NameRegex = '^[A-Za-z]+$';

This code will match the values you're looking for.

As an alternative, you can also match against \p{Alpha}:

String NameRegex = '^\\p{Alpha}+$';

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.