0

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.

2
  • I hope this will help you, if you are using .Net msdn.microsoft.com/en-us/library/2k3te2cs(v=vs.80).aspx Commented Nov 21, 2011 at 12:27
  • I don't know why this was tagged c# and java, but since the accepted answer is in Java, I've removed the other tag. Commented Nov 21, 2011 at 14:06

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

6 Comments

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.
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.
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."
Actually I was asking - how to do it with regex.
@Barun have a look at my edit. And you should update your question to contain this requirement aswell.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.