每个备用 space 的正则表达式模式

Regex pattern for every alternate space

我有以下行

17 3 33 79 38 3 23 119 36 3 27 17 32 10 18 9 93 6

我想用一个词替换每个替代 space,比如 'x',这样它看起来像

17 3x33 79x38 3x23 119x36 3x27 17x32 10x18 9x93 6

我正在使用 Python 3.

尝试过这种模式,但它正在替换每个 space

(?=\d{0,3})(?=\s\d{0,4})\s

您可以将“每个其他 space”定义为“每个 space 后面只有数字对,直到字符串末尾”

\s(?=(?:\b\d{1,3}\s\d{1,3}\b\s*)*$)

细分:

\s            # the space we're going to replace
(?=           # positive look-ahead
  (?:         #   non-capturing group
    \b        #     a word boundary (don't match partial numbers)
    \d{1,3}   #     a number 
    \s        #     a space in-between (implicit \b)
    \d{1,3}   #     a number
    \b        #     a word boundary
    \s*       #     a connecting space to the next number pair (or none at the end of the string)
  )*          #   end non-capturing group, repeat ("only pairs of numbers")
  $           #   end of string ("until the end of the string")
)             # end look-ahead

到select 其他 space,你可以在$.[=17之前添加一个\d{1,3} =]


但实际上,我可能不用正则表达式就可以解决这个问题。

input_str = '17 3 33 79 38 3 23 119 36 3 27 17 32 10 18 9 93 6'
numbers = numbers = input_str.split(' ')

output_str = ''.join([n + ('x' if i % 2 else ' ') for i, n in enumerate(numbers)])
# => '17 3x33 79x38 3x23 119x36 3x27 17x32 10x18 9x93 6x'

output_str = output_str.rstrip('x')
# => '17 3x33 79x38 3x23 119x36 3x27 17x32 10x18 9x93 6'

或者,更喜欢 itertools(尽管我个人更喜欢上面的):

from itertools import cycle

input_str = '17 3 33 79 38 3 23 119 36 3 27 17 32 10 18 9 93 6'

pairs = zip(input_str.split(' '), cycle([' ', 'x']))
# => [('17', ' '), ('3', 'x'), ('33', ' '), ... ]

output_str = ''.join(p for pair in pairs for p in pair)
# => '17 3x33 79x38 3x23 119x36 3x27 17x32 10x18 9x93 6x'

output_str = output_str.rstrip('x')
# => '17 3x33 79x38 3x23 119x36 3x27 17x32 10x18 9x93 6'