0

I have a regular expression: \d+|[a-z]+. What this does is, if you have 81a, it splits into 81 and a. I have tested it on Regex101 and it works fine. I use it in my JavaScript code using match and works fine there too.

The problem is I need use this in my apex class, but unfortunately it doesn't work. I used both

String numberAddress = '818a';
Boolean test = Pattern.matches('/\\d+|[a-z]+/ig', numberAddress);
List<String> splitted = numberAddress.split('/\\d+|[a-z]+/ig');

On doing system debug I get test as false and splitted as a list with one element 818a and not (818, a).

Any ideas how to make it work?

1
  • The forward slashes in regular expression syntax for Javascript are not actually part of the expression.
    – Adrian Larson
    Commented Feb 9, 2021 at 14:48

2 Answers 2

2

Your use case of splitting letters and numbers into separate groups is a good match for String.splitByCharacterType(), which splits a string into groups of contiguous characters of a single character type (as defined by Java's Character.getType()).

String numberAddress = '818a';
List<String> splitted = numberAddress.splitByCharacterType();
System.debug('splitted: ' + JSON.serialize(splitted)); 

This will output:

07:45:28.160 (161909627)|USER_DEBUG|[3]|DEBUG|splitted: ["818","a"]
1

Split isn't the same as match. If you split, you're going to get no output, because the parameter is a boundary match. To get the results you expect, use a Matcher:

String numberAddress = '818a';
Pattern p = Pattern.compile('(\\d+)|([a-zA-Z]+)');
Matcher m = p.matcher(numberAddress);
while(m.find()) {
    system.debug(m.group(0));
}

Note also that the /.../ig form of RegExp only works in JavaScript, Perl, and a few other languages. For Apex, you can use the inline flag set instead:

Pattern p = Pattern.compile('(?i)(\\d+)|([a-z]+)');

The g flag is unnecessary for a Matcher, as it will iterate through each successful match when you use find().

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .