英文:
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'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)?
请注意,如果您不打算捕获任何组的内容,可以将它们更改为非捕获组,这可以提高性能,因为组匹配不需要被提取:
(?: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)?
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)?
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论