Java logic code - Delete some text from a String
I want to remove any occurence of "is happy" sentence from a very large text ignoring case sensitivity. Here are some of that large text sentences :
"She is happy. I like that."
"His happy son"
"He is happy all the day"
"Tasha is Happy"
"Choose one of the following: is sad-is happy-is crying"
My initial code is :
String largeText = "...."; // The very large text her开发者_JS百科e.
String removeText = "is happy";
largeText = largeText.replaceAll( "(?i)" + removeText , "" );
This code will work fine with sentence number 1, 3, 4, 5. But i do not want to delete it from sentence number 2 as it has another meaning. How can i do that ?
Use \b
around your pattern to detect word boundaries. ie:
String largeText = "...."; // The very large text here.
String removeText = "is happy";
largeText = largeText.replaceAll( "(?i)\\b" + removeText + "\\b" , "" );
You might want to look into atomic zero-width assertions -- patterns that match against positions inside a string (such as a word boundary), rather than text itself.
This question was previously asked; see this link for more info:
java String.replaceAll regex question
精彩评论