Alvaro Bilbao
Alvaro Bilbao

Reputation: 23

regular expression to match a number on a String of numbers that are separated by spaces

I have a string such as:

String s = " 10 5 15 55 5 ";

and I'm trying to get the number of repetitions of a number (in this case 5), using a regExp, so my approach is the following:

long repetitions = s.split(" 5").length -1;

but this is not working, it also matches 55.

If I use spaces in both sides of the number, things like:

String s=" 10 10 15 5 ";
long repetitions = s.split(" 10 ").length -1;

it doesn't work, it only counts one instance of 10 (I have two).

So my question is which regExp could be able to count both cases correctly?

Upvotes: 0

Views: 64

Answers (1)

Nir Alfasi
Nir Alfasi

Reputation: 53565

You can use the pattern-matching with the regex '\b5\b' that uses word-boundaries to look for the 5's that are not "part of something else:

String s = " 10 5 15 55 5 ";
Pattern p = Pattern.compile("(\\b5\\b)");
Matcher m = p.matcher(s);
int countMatcher = 0;
while (m.find()) { // find the next match
    m.group();
    countMatcher++; // count it
}
System.out.println("Number of matches: " + countMatcher);

OUTPUT

Number of matches: 2

You can do the same for the 10's and etc.

Upvotes: 1

Related Questions