简体   繁体   中英

Java Regex - need help on number match

I am trying to match all the values 1 to 18 from string 24-15-7-49-63-2 using regex. I used regex before for general purpose but I don't have any idea how to do it.

The tricky thing is that you cannot easily define ranges with regexes. But this might do what you want:

\b([1-9]|1[0-8])\b

You can see it in action here: http://regexr.com?2v8jj

Here's an example in java:

String text = "24-15-7-49-63-2";
String pattern = "\\b([1-9]|1[0-8])\\b";

Pattern compiledPattern = Pattern.compile(pattern);
Matcher matcher = compiledPattern.matcher(text);
while (matcher.find()) {
    System.out.println(matcher.group());
}

Outputs:

15
7
2

Edit: Based on the comment you can get unique matches using this pattern:

\b([1-9]|1[0-8])\b(?!.*\b\1\b.*)

In action: http://regexr.com?2v8kh

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