Simple regexp match
What's the correct regex to match such set [1] [2] [3] [4] [23]
- where numbers are inside the brackets. (I need to get the brackets thoug开发者_C百科h)
The regex \[[0-9]+\] will match anything like '[1]', '[2]', '[678]'. A more precise regex, which catches one or more of these patterns in sequence, is:
((\[[0-9]+\])( |$))+
I'm not familiar with Java regex, but if it's PCRE, I think it should be:
/(\[\d+\])/
I wasn't exactly sure if you need the brackets in the match, but if you don't, I think you could use
/\[(\d+)\]/
If you don't need to capture any of the numbers the following expression will match a string with that pattern:
(?:\[\d+\]\s?)+
The following seems to work:
Pattern pattern = Pattern.compile("(\\[\\d+\\])\\s*");
Matcher matcher = pattern.matcher("[1] [2] [3] [4] [23]");
while (matcher.find()) {
System.out.println("match = " + matcher.group(1));
}
精彩评论