【问题标题】:Regex to match end-of-sentence markers [closed]正则表达式匹配句尾标记[关闭]
【发布时间】:2014-09-23 08:18:50
【问题描述】:

我需要匹配给定正文中的所有句尾符号,例如 !?.(句点)等。

谁能帮我用正则表达式来做这样的事情?

示例输入:

This is the f!!rst sentence! Is this the second one? The third sentence is here... And the fourth one!!

输出:

This is the f!!rst sentence Is this the second one The third sentence is here And the fourth one

【问题讨论】:

  • 在提出任何问题时,请记住提供示例输入和预期输出。这将阻止仅基于假设的答案。
  • 你已经调查和尝试了什么?
  • 如果您提出的问题不仅仅对您有用,人们会帮助您。这里不是这种情况。
  • 对不起,我有点急,因为我的大学项目需要这个,基本上我正在构建一个搜索引擎原型,我需要标记数据源中包含 10,000 个的每个单词+ 新闻文章。过滤的任务之一是删除像!,?, 这样的符号。出现在句末作为标记。

标签: java regex


【解决方案1】:
[!?.]+(?=$|\s)

试试这个。你可以根据需要添加标记。替换为``。

查看演示。

http://regex101.com/r/lS5tT3/15

【讨论】:

  • 正是我想要的!谢谢你。顺便问一下,能推荐一个学习reg表达式的好方法吗?我迟早要掌握这些东西,所以我需要一个可以开始的好地方
  • @user2306772 立即尝试。
  • @user2306772 查看您的示例。您也已从中间删除了所有内容。先更正它。
  • 希望问题现在已经清楚了!
  • 好吧,我可能喝多了红牛……再次抱歉!
【解决方案2】:

您可能想要匹配任何内容 (.*?),然后是句末,然后是空格 (\s+)。自从 !, ?和 。是特殊字符,您需要将它们排除在外。

例如

Pattern pattern = Pattern.compile("(.*?)[\\!\\?\\.]\\s+");
Matcher matcher = pattern.matcher("one two. three! four five? ");
while (matcher.find()) {
   System.out.println(matcher.group(1));
}

打印

one two
three
four five

【讨论】:

  • 这个答案对任何人都不是特别有帮助。问题本身并不清楚。
  • 认真的吗?我想我已经解释得足够让大脑思考了。下次我就不打扰了。
  • 我可能以非常随意的方式问这个问题搞砸了。我很着急,需要一些快速的帮助,并没有费心详细说明。无论如何,我已经进行了编辑。 Lance Java,您的回答当然很有帮助,但我想这不是我想要的。
【解决方案3】:

下面的正则表达式将匹配非单词字符(空格除外),这些字符必须后跟空格字符或行尾锚。 replaceAll 函数有助于删除所有匹配的字符。

String s = "Blah! blah? blah... blah blah!!";
System.out.println(s.replaceAll("[^\\w\\s]+(?=\\s|$)", ""));

输出:

Blah blah blah blah blah

如果您只想删除单词最后出现的?.! 字符,您可以尝试以下代码。

String s = "This is the f!!rst sentence! Is this the second one? The third sentence is here... And the fourth one!!";
System.out.println(s.replaceAll("[!?.]+(?=\\s|$)", ""));

输出:

This is the f!!rst sentence Is this the second one The third sentence is here And the fourth one

【讨论】:

  • 非常感谢! vks 的解决方案和你的解决方案都很好!
  • @user2306772 你没有尝试编辑过的
  • @vks 我在您编辑之前发布了答案。查看修订。
  • @AvinashRaj 问题不断变化。
  • 抱歉给我带来了麻烦!下一次,我应该花一些时间更清楚地阐述这个问题
猜你喜欢
  • 2011-04-01
  • 1970-01-01
  • 2011-07-30
  • 2013-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多