繁体   English   中英

正则表达式提取任意数量的子模式

[英]Regex extract arbitrary number of subpatterns

我的句子具有结构“名称有 digit1 word1、digit2 word2、...和 digitN wordN”,其中子模式“数字词”的数量因句子而异,因此不确定。 最后一个子模式之前有一个“and”。 例如“爱丽丝有 1 个苹果、2 个香蕉、……和 6 个橙子。”

如何在 python 中使用正则表达式提取这些数字和单词? 我希望 output 如下:

姓名,

数字 单词
数字1 单词1
数字2 字2
... ...
数字N 单词N

我尝试了以下方法:

s = 'Alice has 1 apple, 2 bananas, and 3 oranges.'
import re
matches = re.finditer(r'([Aa-z]+) has (\d) ([a-z]+)( and)*', s)
for match in matches:
  print(match.groups())

但这只会给我('Alice','1','apple',None),缺少'2','bananas','3','oranges'。

如果您想在单个正则表达式中匹配所有内容,则需要这样的内容:

([^\s]+) has (?:(?:,\s+)?(?:and\s+)?(\d+)\s+([^\s,]+)){1,}

正则表达式演示

但是,我不确定 python 是否可以处理重复组。 至少,我还没有找到从 python object 中提取重复组的方法。

所以这是我建议解决问题的方法:

import re

s = 'Alice has 1 apple, 2 bananas, and 3 oranges.'

matches = re.match(r'^([^\s]+)', s)
print(f'Name: {matches.group(0)}')

matches = re.findall(r'(?:(?:,\s+)?(?:and\s+)?(\d+)\s+([^\s,]+))', s)

for match in matches:
    print(f'{match[0]} - {match[1]}')

样品 Output

Name: Alice
1 - apple
2 - bananas
3 - oranges.

Process finished with exit code 0

正则表达式说明

^([^\s]+) - 很少有不同的方法来解决这个问题,但它只是抓取所有内容,直到字符串中的第一个空格。

(?:           - Non-capturing group
 (?:,\s+)?    - Optionally allow the string to have a `,` followed by spaces
 (?:and\s+)?  - Optionally allow the string to contain the word `and` followed by spaces
 (\d+)        - Must have a number
 \s+          - Spaces between number and description
 ([^\s,]+)    - Grab the next set of characters and stop when you find a space or comma. This should be the word (e.g. apple)
)

第二个正则表达式只是确保您可以提取1 apple的各种 forms 。 所以它基本上会匹配以下模式:

  • 1 apple
  • , 1 apple
  • , and 1 apple
  • and 1 apple

作为旁注,从长远来看,解析器更适合这些问题。 你在句子中得到了更多的变化,并且使用简单的正则表达式开始变得非常难以解析。

使用PyPi 正则表达式

参见 Python 代码

import regex
s = 'Alice has 1 apple, 2 bananas, and 3 oranges.'
matches = regex.finditer(r'(?P<word1>[A-Za-z]+) has(?:(?:\s+|,\s+|,?\s+and\s+)?(?P<number>\d+)\s+(?P<word2>[a-z]+))*', s)
for match in matches:
  print(match.capturesdict())

结果{'word1': ['Alice'], 'number': ['1', '2', '3'], 'word2': ['apple', 'bananas', 'oranges']}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM