Java逻辑代码-从字符串中删除一些文本

发布于 2024-10-08 20:29:28 字数 485 浏览 3 评论 0原文

我想从非常大的文本中删除任何出现的“很高兴”句子,忽略大小写。以下是一些大文本句子:

  1. “她很高兴。我喜欢那个。”

  2. “他快乐的儿子”

  3. “他一整天都很快乐”

  4. “塔莎很快乐”

  5. “选择以下之一:伤心-高兴-哭”

我的初始代码是:

String largeText = "....";  // The very large text here.
String removeText = "is happy";
largeText = largeText.replaceAll( "(?i)" + removeText , "" ); 

此代码适用于第 1、3、4、5 句。但我不想将其从第 2 句中删除,因为它有其他含义。 我该怎么做?

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 here.
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 ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

江南月 2024-10-15 20:29:28

在模式周围使用 \b 来检测单词边界。 IE:

String largeText = "....";  // The very large text here.
String removeText = "is happy";
largeText = largeText.replaceAll( "(?i)\\b" + removeText + "\\b" , "" ); 

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" , "" ); 
无语# 2024-10-15 20:29:28

您可能想要研究原子零宽度断言 - 与字符串内的位置匹配的模式(例如单词边界),而不是文本本身。

这个问题以前曾被问过;有关详细信息,请参阅此链接:

java String.replaceAll 正则表达式问题

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文