Java word filter using regex?

I am trying to create a word filter where the user can replace certain words with others. However, obviously, there are some things that I do not want to filter (for example, words that are different from other words).

So far I have this:

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

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

When I replace “m” with, say, “r”, then it also replaces “m” with the words “I'm” - this means that it becomes “I'r”, which is obviously a mistake.

I hope you understand what I mean. Help?

+4
source share
1 answer

How about something like that?

 //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); 
+1
source

Source: https://habr.com/ru/post/1485064/


All Articles