John Smith
John Smith

Reputation: 139

Java word filter using regex?

I'm trying to create a word filter where a user can replace certain words with others. However, there are obviously some things that I don't want it to filter (words that are apart of other words, for example).

So far I have this:

msg = msg.replaceAll("(?i)\\b[^\\w -]*"+original+"[^\\w -]*\\b", replacement);

It, for the most part, works relatively well. However, there is one small glitch.

When I replace "m" with, let's say, "r" then it also replaces the "m" in words like "I'm" - which means it becomes "I'r", which is obviously a bug.

I hope you understand what I mean. Help?

Upvotes: 4

Views: 765

Answers (1)

Lone nebula
Lone nebula

Reputation: 4878

How about something like this?

//If "X-Men" counts as one word:
msg = msg.replaceAll("(?i)(?<![\\w'-])"+original+"(?![\\w'-])", replacement);
//If "X-Men" counts as two words:
msg = msg.replaceAll("(?i)(?<![\\w'])"+original+"(?![\\w'])", replacement);

Upvotes: 1

Related Questions