开发者

REGEX a word in a paragraph, but not a word containing that word, unless its a plural

I am highlighting words in a bo开发者_如何转开发dy of text.

If I regex "Port" the word "Portuguese" is highlighted too, but I need "Ports" to be highlighted.

Any ideas? I hate regex.

Thanks


Try something like this:

\bports?\b

The ? means that the s character is optional. The \b at either end matches word-boundaries.

More generally, you could do something like this to allow words ending in s, es or ies:

\bwhatever(?:s|es|ies)?\b

This is very crude and you're likely to get false positives and negatives. If you want something more sophisticated then I suppose you'd need to look at a proper full-text search engine.


The most basic answer would be this:

\bPort(s?)\b

\b marks beginning and ending of the word. This only matches 'Port' and 'Ports'. If you need case insensitive matching, then use something like /i modifier in Perl:

m/\bport(s?)\b/i

Or, if you want to match only 'port', 'Port', 'ports' and 'Ports', try

\b(P|p)ort(s?)\b
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜