根据正则表达式中的字母数字连接生成变体

2024-10-04 03:16:16 发布

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

我有一个单词列表,有些是单字,有些是多字,这些单词可能有数字字符,也可能没有数字字符。你知道吗

举个例子-

word_list=['word', 'kap1','another word', 'another-1 word', 'another word 1']

我想确定列表中的单字条目,形式如下-

alphabets*Junction*digit(s)

其中连接可以是空格、连字符或无。例如,在上面的列表中,kap1限定(没有其他条目限定)。现在,找到这个条目后,我想创建这个条目的变体(基于连接),并将它们添加到列表中。你知道吗

例如,在找到kap1之后,我想将kap 1kap-1添加到列表中。你知道吗

我能写出识别条目的初始正则表达式-

Word_NumberRegex=re.compile(r"^[a-zA-Z]+[ -]?\d+$")

但是我想知道一个好的算法来创建变体,这取决于连接。你知道吗


Tags: 目的列表another条目数字变体字符单词
2条回答

您可以使用3个捕获组并使用中间组捕获连接角色。使用连接字符搜索分隔符列表并获得所需的输出:

import re

word_list=['word', 'kap1', 'another word', 'abc-123', 'another-1 word', 'another word 1']

reg = re.compile(r'^([a-zA-Z]+)([- ]?)([0-9]+)$')

for w in word_list:
   m = reg.match(w)
   if m:
      result = []
      seps = ['', ' ', '-']
      seps.remove(m.group(2))
      for s in seps:
         result += [m.group(1) + s + m.group(3)]
      print result

输出:

['kap 1', 'kap-1']
['abc123', 'abc 123']

Code Demo

使用re,您可以捕获匹配的模式,并使用自定义分隔符重新格式化:

word_list=['word', 'kap1','another word', 'another-1 word', 'another word 1']

import re    
p = r'([a-zA-Z]+)[- ]?([0-9]+)'
[re.sub(p, r'\1{}\2'.format(sep), w) for w in word_list if re.fullmatch(p, w) for sep in ['', ' ', '-']]

# ['kap1', 'kap 1', 'kap-1']

预编译模式:

p = re.compile(r'([a-zA-Z]+)[- ]?([0-9]+)')
[p.sub(r'\1{}\2'.format(sep), w) for w in word_list if p.fullmatch(w) for sep in ['', ' ', '-']]
​
# ['kap1', 'kap 1', 'kap-1']

相关问题 更多 >