qwerty
qwerty

Reputation: 5266

RegEx: Match "year:2012" anywhere in a string?

I'm working on a search engine, and i need the user to be able to filter the results by year. I want the user to be able to add "year:(four digits)" anywhere in the search string. I created this but it's not quite what i want:

(year\:\d{4})

It does indeed match what i need, but i only want to match if there is either whitespace or nothing next to it. Right now, it matches even if it's in the middle of a word.

Examples:

testyear:2012test - Don't want match
test year:2012test - Don't want match
test year:2012 test - DO want match
test year:2012 - DO want match

Any ideas?

Upvotes: 2

Views: 223

Answers (2)

Blender
Blender

Reputation: 298582

You can use word boundaries:

\b(year:\d{4})\b

Upvotes: 3

xdazz
xdazz

Reputation: 160973

Use the below regex:

\byear:\d{4}\b

\b matches the word boundary

Upvotes: 2

Related Questions