Elliott
Elliott

Reputation: 5609

Regular Expression Java non alpha numeric character matching

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.

Upvotes: 0

Views: 401

Answers (2)

Bohemian
Bohemian

Reputation: 425418

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.

Upvotes: 0

Andrew Clark
Andrew Clark

Reputation: 208705

Try the following:

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

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

Upvotes: 2

Related Questions