Wayne Moir
Wayne Moir

Reputation: 28

Regular expression to match whole words

I am trying use a regular expression in JavaScript to match instances of the word 'icon-' in a string and return the entire attached word up to the delimiter (space). An example of the string would be

ui-grid-ico-sort icon icon-up ui-icon-asc icon-user ui-icon ui-icon-triangle-1-n ui-sort-ltr

In this case I am trying to match only 'icon-up' and 'icon-user'.

So far I have tried \bicon- which appears to match every instance of icon- regardless of its placement in a word (4 matches) and \bicon-[^'"]+ which returns 1 match of everything after the first instance of icon-

Upvotes: 0

Views: 421

Answers (3)

Phan
Phan

Reputation: 114

This is the regular expression:

\bicon-[^\b]+?\b

By using \b, this expression can also match the "icon-up" in these cases:

icon,icon-up
icon,icon-up,icon-down

Upvotes: 0

Tim Pietzcker
Tim Pietzcker

Reputation: 336158

(^|\s)icon-\S+

matches all words that start with icon-up to the next whitespace character.

You will need to remove a leading space character, if present. There is no other way because JavaScript doesn't support lookbehind assertions.

Explanation:

(^|\s)  # Match start of string or whitespace
icon-   # Match icon-
\S+     # Match one or more non-whitespace characters.

Upvotes: 3

burning_LEGION
burning_LEGION

Reputation: 13450

use this regular expression: (^|\s)icon-\S+

Upvotes: 0

Related Questions