2

I have been trying to get the number of numbers in a string using regex, but without success. The following code returns me 0 groups in the expression.

String expression = '1 OR (2 OR 3) AND 4';
Matcher m = Pattern.compile('\\d').matcher(expression);
System.debug(m.groupCount());

What am I doing wrong here? I want the number of elements and, if possible, the value, so I can make this a map. Using the example provided, I would have a map like:

m.group(0) => 1
m.group(1) => 2
m.group(2) => 3
m.group(3) => 4

2 Answers 2

2

Following on the first answer provided...

You'll likely want to change your pattern from '\\d' to '\\d+' . the reason is, if you get enough filters to hit more than 9 items, the matcher will interpret "10" as "1" and "0". Changing your pattern to '\\d+' will correctly interpret "10" as "10".

Bonus> I've added a List to capture the integer values.

String expression  = '1 OR (2 OR 3) AND 4 OR 16';

pattern myPattern = pattern.compile('\\d+'); 
matcher myMatcher = myPattern.matcher(expression);


List<Integer> myIntegers = new List<Integer>();

if(myMatcher.find()) {
  do {

        system.debug( '-->>' + myMatcher.group() );
        myIntegers.add(Integer.valueOf(myMatcher.group()));

  } while(myMatcher.find());

}

Helpful answer frm previous post: How to find all numbers in a string using Regex

3

Uou can use matcher.find() to get all the numbers in loop. Hope this helps.

Apex code

String expression = '1 OR (2 OR 3) AND 4';
Pattern ptn = Pattern.compile('(\\d+)');
Matcher m = ptn.matcher(expression);

if(m.find()) {
  do {
    system.debug( '====' + m.group() );
  } while(m.find());
}

You must log in to answer this question.

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