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.
1 Answer
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
6 Comments
Barun
Great thanks man. Please help me out a little more. How can I write this so that it wont capture which appeared before? I mean wont capture repeated value.
Marcus
You'll probably don't want to do that with regex but in your code. One solution would be to add each match to a set which holds only unique numbers.
Marcus
If you're using Java have a look at: download.oracle.com/javase/6/docs/api/java/util/Set.html. The first line says: "A collection that contains no duplicate elements."
Barun
Actually I was asking - how to do it with regex.
Marcus
@Barun have a look at my edit. And you should update your question to contain this requirement aswell.
|
c#andjava, but since the accepted answer is in Java, I've removed the other tag.