正则表达式:字符串开头的重复模式

2024-06-23 19:29:31 发布

您现在位置:Python中文网/ 问答频道 /正文

例如,考虑以下字符串:"apple1: apple2: apple3: some random words here apple4:"

我只想匹配apple1、apple2和apple3,但不想匹配apple4。我很难弄清楚如何存档

感谢您的帮助

谢谢


Tags: 字符串hererandomsomewordsapple1apple4apple3
3条回答

如果您使用的是.net,那么可以匹配下面的模式,然后使用组的Captures属性来匹配所有不同的apple

(?:(apple\d).*?){3}

如果只想匹配第一个:

apple\d

甜蜜而简单。就给match打一次电话

所以,也许是这样的:

^([A-Za-z]+)[^A-Za-z]+(\1[^A-Za-z]+)+

http://regexr.com/38vvb

从您的注释来看,似乎您希望匹配整个字符串中出现的apple后跟一个数字,但出现的apple后跟字符串末尾的数字除外

>>> import re
>>> text    = 'apple1: apple2: apple3: some random words here apple4:'
>>> matches = re.findall(r'(\bapple\d+):(?!$)', text)

['apple1', 'apple2', 'apple3']

相关问题 更多 >

    热门问题