Ryckes
Ryckes

Reputation: 34

Is there a regex symbol to match one, the other, or both (if possible)?

I want to highlight a group of words, they can appear single or in a row. I'd like them to be highlighted together if they appear one after the other, and if they don't, they should also be highlighted, like the normal behavior. For instance, if I want to highlight the words:

results as

And the subject is:

real time results: shows results as you type

I'd like the result to be:

real time results: shows <span class="highlighted"> results as </span> you type

The whitespaces are also a headache, because I tried using an or expression:

( results )|( as )

with whitespaces to prevent highlighting words like bass, crash, and so on. But since the whitespace after results is the same as the whitespace before as, the regexp ignores it and only highlights results.

It can be used to highlighted many words so combinations of

( (one) (two) )|( (two) (one) )|( one )|( two )

are not an option :(

Then I thought that there may be an operator that worked like | that could be use to match both if possible, else one, or the other.

Upvotes: 0

Views: 1205

Answers (2)

JDB
JDB

Reputation: 25855

Perhaps you do not need to match a string of words next to each other. Why not just apply your highlighting like so:

real time results: shows <span class="highlighted">results</span> <span class="highlighted">as</span> you type

The only realy difference is that the space between the words is not highlighted, but it's a clean and easy compromise which will save you hours of work and doesn't seem to hurt the UX in the least (in my opinion).

In that case, you could just use alternation:

\b(results|as)\b

(\b being the word boundary anchor)

If you really don't like the space between words not being highlight, you could write a jQuery function to find "highlighted" spans separated by only white space and then combine them (a "second stage" to achieve your UX design goals).

Update
(OK... so merging spans is actually kind of difficult via jQuery. See Find text between two tags/nodes)

Upvotes: 3

Martin Ender
Martin Ender

Reputation: 44279

Using spaces to ensure you match full words is the wrong approach. That's what word boundaries are for: \b matches a position between a word and a non-word character (where word characters usually are letters, digits and underscores). To match combinations of your desired words, you can simply put them all in an alternation (like you already do), and repeat as often as possible. Like so:

(?:\bresults\b\s*|\bas\b\s*)+

This assumes that you want to highlight the first and separate results in your example as well (which would satisfy your description of the problem).

Upvotes: 5

Related Questions