Stim
Stim

Reputation: 1465

What regex matches string within wordbounds, but not next to '@'

I want to find the number of occurrences of a certain string in a text. The string can match the beginning of a sentence or at the end before the '.'. So I thought of:

\bMY_STRING\b

However, i do not want to match parts of an email address. That is, the string should not be next to the @ (at-sign, at-symbol, ampersat, apetail, arroba, atmark, at symbol, commercial at, monkey tail or whatever term makes it easier to find this using a search engine).

So, 'example' should not be counted in '[email protected]'.

What should replace the \b in my expression to match wordbreaks, except at @?

Upvotes: 1

Views: 811

Answers (3)

SERPRO
SERPRO

Reputation: 10067

I think you can use the lookbehind and lookahead options in regex:

#\b(?<![@])YOUR_TEXT(?![@])\b)#

Example

Upvotes: 1

Tim Pietzcker
Tim Pietzcker

Reputation: 336158

If your regex flavors knows lookbehind assertions (most do, but JavaScript and Ruby 1.8 only support lookahead), you can replace all \bs with this:

(?<!@)\b(?!@)

This matches a word boundary only if it's not before or after a @.

Upvotes: 4

Igor
Igor

Reputation: 27250

You can use:

[^\@] 

which means: match any character except @

Upvotes: 0

Related Questions