正则表达式根据连字符的出现情况来匹配句子中单词中的连字符

发布于 2025-01-19 17:43:27 字数 306 浏览 2 评论 0原文

我正在尝试匹配单词中的连字符,但前提是连字符在该单词中出现多次,

因此在短语“Step-By-Step”中连字符将被匹配,而在短语“Coca-Cola”中,连字符将被匹配连字符将不匹配。

在组合短语“Step-By-Step and Coca-Cola”的完整句子中,只有“Step-By-Step”中的连字符才会匹配。

我当前有以下表达式,但是这匹配所有由非数字字符分隔的连字符,无论出现什么情况,

((?=\D)-(?<=\D))

我似乎无法让量词与该表达式一起使用,有什么想法吗?

I am trying to match on hyphens in a word but only if the hyphen occurs in said word say more than once

So in the phrase "Step-By-Step" the hyphens would be matched whereas in the phrase "Coca-Cola", the hyphens would not be matched.

In a full sentence combining phrases "Step-By-Step and Coca-Cola" only the hyphens within "Step-By-Step" would be expected to match.

I have the following expression currently, but this is matching all hyphens separated by non-digit characters regardless of occurences

((?=\D)-(?<=\D))

I can't seem to get the quantifiers to work with this expression, any ideas?

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

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

发布评论

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

评论(2

音盲 2025-01-26 17:43:27

Java 正则表达式解决方案:

(?<=-[^\s-]{0,999})-|-(?=[^\s-]*-)

Java 正则表达式演示


PCRE 正则表达式解决方案:

这是一种在 PCRE 中匹配具有多个连字符的行中的所有连字符的方法:

(?:(?:^|\s)(?=(?:[^\s-]*-){2})|(?!^)\G)[^\s-]*\K-

正则表达式演示

说明:

  • [^\s-]* 匹配非空格且非连字符的字符
  • (?=(?:[^\s-]*-){2}) 是向前查找,以确保非空白子字符串中至少有 2 个连字符
  • \G主张立场在上一个匹配的末尾或第一个匹配的字符串的开头
  • \K 重置匹配信息

Java Regex Solution:

(?<=-[^\s-]{0,999})-|-(?=[^\s-]*-)

Java RegEx Demo


PCRE Regex Solution:

Here is a way to match all hyphens in a line with more than one hyphen in PCRE:

(?:(?:^|\s)(?=(?:[^\s-]*-){2})|(?!^)\G)[^\s-]*\K-

RegEx Demo

Explanation:

  • [^\s-]* matches a character that is not a whitespace and not a hyphen
  • (?=(?:[^\s-]*-){2}) is lookahead to make sure there are at least 2 hyphens in a non-whitespace substring
  • \G asserts position at the end of the previous match or the start of the string for the first match
  • \K resets match info

爱的故事 2025-01-26 17:43:27

这至少匹配两个单词,每个单词后跟连字符,后跟另一个单词(我假设您不想在开头或结尾允许连字符,仅在单词之间使用)。

(\w+-){2,}\w+

This matches at least two words each followed by hyphen, followed by another word (I'm assuming you don't want to allow hyphen at the very beginning or end, only between words).

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