开发者

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 :

  1. "She is happy. I like that."

  2. "His happy son"

  3. "He is happy all the day"

  4. "Tasha is Happy"

  5. "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

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜