0

I want to match an expression like this:

500 q 6h

Where the numbers can be any integer (thus 2 q 500h is also a legal expression).

I'm trying to match this pattern using the following regular expression (\W|^)\d+ q \d+h(\W|$)

Using this pattern, I would expect a string like

a500 q 6h to be not matched. Instead it is matched.

Similarly, I would expect a string like

(500 q 6h) to be matched, but it is not matched.

I don't get what I'm doing wrong.

7
  • ^[0-9]+ q [0-9]+h$ should work Commented Apr 30, 2013 at 22:30
  • Is the expression in your question directly copied and pasted from your code? I ask because \W\$ is almost certainly incorrect, and there's likely a + missing after the second \d also. Be sure that your \W are actually uppercase. Commented Apr 30, 2013 at 22:32
  • @CorvinMcpherson That wouldn't match (500 q 6h) though. Commented Apr 30, 2013 at 22:34
  • ^\(?[0-9]+ q [0-9]+h\)?$ revised to match (500 q 6h) Commented Apr 30, 2013 at 22:34
  • 1
    @Elliott: show your relevant code ;) Commented Apr 30, 2013 at 22:43

2 Answers 2

2

Try the following:

(?<!\w)\d+ q \d+h(?!\w)

For example: http://www.rubular.com/r/IY6T8GvK7D

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

Comments

0

Try this (note double backslashes required by java in String literals)

\\b\\d+ q \\d+h

I've used the "word boundary" regex \b to handle the "preceding letter" issue.

Comments

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.