简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM