提取特定字母后的文本和整数

jez*_*ael 0 python regex integer split list

我有字符串:

s = 'travel to africa x 2\ asia x 2\ europe x 2\ Airport pick up included. Furnitures 3 seater couch x 1 4 seater+ couch x 1 < 60 inches TV x 1 60 inches+ TV x 1 Washer - front loader x 1 Box / bag / misc x 1 The maximum clearance is 1.5m.'
Run Code Online (Sandbox Code Playgroud)

我想将其分割x并在其后提取数字。

因此,预期输出为:

out = [('travel to africa', '2'),
       ('\ asia', '2'),
       ( '\ europe', '2'),
       ('\ Airport pick up included. Furnitures 3 seater couch', '1'),
       ('4 seater+ couch', '1'),
       ('< 60 inches TV', '1'),
       ('60 inches+ TV', '1'),
       ('Washer - front loader', '1'),
       ('Box / bag / misc', '1')]
Run Code Online (Sandbox Code Playgroud)

我尝试使用此正则表达式,但是失败了,因为-+<省略了像这样的特殊字符(也应该有另一个特殊字符):

r'([A-Za-z 0-9]+)\s+x\s+(\d+)'
Run Code Online (Sandbox Code Playgroud)

什么是提取此值的正确正则表达式?还是没有正则表达式的可能解决方案?

Wik*_*żew 8

您可以使用

re.findall(r'(.*?)\s+x\s*(\d+)', s)
Run Code Online (Sandbox Code Playgroud)

请参阅Python演示regex演示

(.*?)\s+x\s*(\d+)模式匹配

  • (.*?) -第1组:除换行符以外的任何0+个字符
  • \s+ -1+空格
  • x- x字符
  • \s* -0+空格
  • (\d+) -第2组:一个或多个数字。

如果您想在比赛开始时消除空格,re.findall(r'(\S.*?)\s+x\s*(\d+)', s)请在获取所有比赛之后使用或(参见regex demo)或使用理解[x.strip() for x in re.findall(r'(.*?)\s+x\s*(\d+)', s)]