简单的 Java 正则表达式不起作用

发布于 2024-09-29 16:36:43 字数 434 浏览 0 评论 0 原文

我有这个正则表达式,它应该删除句子分隔符(.?):

sentence = sentence.replaceAll("\\.|\\?$","");

它工作正常,可以转换

“我是 Java 开发人员。”“我是 Java 开发人员”

“我是 Java 开发人员吗?”“我是 Java 开发人员吗”

但部署后我们发现它还会替换句子中的任何其他点,因为

“Hi.Am I a Java Developer?” 变为 “HiAm I a Java Developer”

为什么会发生这种情况?

I have this regex which is supposed to remove sentence delimiters(. and ?):

sentence = sentence.replaceAll("\\.|\\?$","");

It works fine it converts

"I am Java developer." to "I am Java developer"

"Am I a Java developer?" to "Am I a Java developer"

But after deployment we found that it also replaces any other dots in the sentence as

"Hi.Am I a Java developer?" becomes "HiAm I a Java developer"

Why is this happening?

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

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

发布评论

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

评论(4

剩余の解释 2024-10-06 16:36:43

管道 (|)具有所有运算符中最低的优先级。因此,您的正则表达式:

\\.|\\?$

被视为:

(\\.)|(\\?$)

匹配字符串中的 . 任何位置,并匹配末尾的 ?字符串的strong>。

要解决此问题,您需要将 .? 组合在一起,如下所示:

(?:\\.|\\?)$

您还可以使用:

[.?]$

在字符类中 .? 按字面意思处理,因此您无需转义它们。

The pipe (|) has the lowest precedence of all operators. So your regex:

\\.|\\?$

is being treated as:

(\\.)|(\\?$)

which matches a . anywhere in the string and matches a ? at the end of the string.

To fix this you need to group the . and ? together as:

(?:\\.|\\?)$

You could also use:

[.?]$

Within a character class . and ? are treated literally so you need not escape them.

温暖的光 2024-10-06 16:36:43

您所说的 "\\.|\\?$" 是“句号”“最后一个字符为问号”。

我建议改为 "[.?]$" 以避免令人困惑的转义(当然,也会产生不良结果)。

What you're saying with "\\.|\\?$" is "either a period" or "a question mark as the last character".

I would recommend "[.?]$" instead in order to avoid the confusing escaping (and undesirable result, of course).

╰沐子 2024-10-06 16:36:43

您的问题是由于 优先级 较低。正则表达式.info/alternation.html" rel="nofollow">交替运算符 |。您的正则表达式意味着匹配以下之一:

  • . 任何位置
  • ? 位于行尾。

使用字符类代替:

"[.?]$"

Your problem is because of the low precedence of the alternation operator |. Your regular expression means match one of:

  • . anywhere or
  • ? at the end of a line.

Use a character class instead:

"[.?]$"
海之角 2024-10-06 16:36:43

您忘记了用圆括号括起句子结尾字符:

sentence = sentence.replaceAll("(\\.|\\?)$","");

更好的方法是像 @Mark Byers 建议的那样使用 [.?]$

sentence = sentence.replaceAll("[.?]$","");

You have forgotten to embrace the sentence-ending characters with round brackets:

sentence = sentence.replaceAll("(\\.|\\?)$","");

The better approach is to use [.?]$ like @Mark Byers suggested.

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