目标是针对带有重复的字母组合(例如:?)

huangapple go评论64阅读模式
英文:

Targeting combinations of letters with repetitions (IE: ? )

问题

我尝试创建一个正则表达式,匹配以下语句:

```none
steal
stealer
photograph
photographer

但不能匹配:

steale
photographe

我尝试了以下 Rust 正则表达式,但重复只针对 R 而不是 E:

(steal|photograph)(er?)

注意:这个问题已经从一个更复杂的正则表达式简化,如果有可能的话,避免使用 (steal|stealer|photograph|photographer)。


<details>
<summary>英文:</summary>

I&#39;m trying to create a regular expression that will match the following statements:

```none
steal
stealer
photograph
photographer

But must not match:

steale
photographe

I tried the following RustExp, however the repetition only targets the R and not the E:

(steal|photograph)(er?)

Note: This problem has been simplified from a much bigger regular expression and it's not feasible to use (steal|stealer|photograph|photographer) if it is at all possible to avoid it.

答案1

得分: 2

只需将 ? 移至括号的外部,以便它适用于整个组,而不仅仅是 r 字符:

(steal|photograph)(er)?

(Playground)

请注意,如果您不打算捕获任何组的内容,可以将它们更改为非捕获组,这可以提高性能,因为组匹配不需要被提取:

(?:steal|photograph)(?:er)?
英文:

Just move the ? to the outside of the parens so that it applies to the whole group instead of just the r character:

(steal|photograph)(er)?

(Playground)

Note that if you don't intend to capture the contents of either group, you can change them to non-capturing groups, which can increase performance as the group match doesn't need to be extracted:

(?:steal|photograph)(?:er)?

huangapple
  • 本文由 发表于 2023年4月4日 10:31:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/75925095.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定