0

I am trying to come up with the regex to find strings matching the following pattern:

(someNumber - someNumber) With the parenthesis included.

I tried:

"\\([1-9]*-[1-9]*\\)"

but that doesn't seem to work.

I also need to match:

The letter W or L followed by (someNumber - someNumber) With the parenthesis included.

I tried to use the same pattern above, slightly modified, but again, no luck:

"W|L \\([1-9]*-[1-9]*\\)"

Any help would be appreciated

1
  • Can we see how you are using your regexes? Some code example with input and expected output would be very helpful to find and explain your mistakes. Commented Mar 11, 2014 at 19:55

3 Answers 3

1

Include W|L in parentheses:

(W|L)

If you want to include space characters before and after the minus, add \s or a space before and after -

"((W|L)\\s)?\\([1-9]*\\s-\\s[1-9]*\\)"

If you already know that there will be at least one digit, use + instead of *, as * matches zero or more, whereas + matches 1 or more.

The pattern given above matches with and without a W or L in front. Here's a pattern that matches with and without space around the - and with or without W or L in front. Additionally, it also captures numbers containing 0, which you excluded in your original regular expression.

"((W|L)\\s)?\\(\\d+\\s?-\\s?\\d+\\)"
Sign up to request clarification or add additional context in comments.

8 Comments

When I put in "W (10-5)" I'm only getting the W returned as a match. Wonder why?
See the updated answer and try the last regular expression mentionned. Works for me. How are you retrieving the result? If you are using m.group(1), that returns "W". Use m.group() or m.group(0) to get the whole match.
I'm iterating over the matches(while m.find()), and adding m.group() to an arraylist of Strings.
Do you still only get W, even with the regex as given above?
So it should match 'W (5-10)' right? The 2nd regex string you posted?
|
0

Further to blueygh2's answer, your regex will fail if the numbers contain zeroes. My guess is you want to avoid leading zeroes, in which case use [1-9]\d* (or [1-9][0-9]*). If you want to allow the numbers to equal 0 but otherwise avoid leading zeroes, do ([1-9]\d*|0).

Comments

0

You can try this :
"(W|L)\\s*\\(\\d+-\\d+\\)"

1 Comment

This matches with any number of Ws followed by any number of Ls. We can do better than that!

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.