假设我有以下字符串:
s = 'some text\n\nsome other text'
我现在想将字母“X”添加到包含文本的每一行的末尾,以便输出为 'some textX\n\nsome other textX'。我试过了
re.sub('((?!\S)$)', 'X', s, re.M)
但这只会在字符串末尾添加 'X' 即使它处于多行模式,即输出是 'some text\n\nsome other textX'。我怎么解决这个问题?
请您参考如下方法:
你真的需要正则表达式吗?您可以只拆分换行符,相应地添加 X,然后重新加入。这是一种方法,使用 yield -
In [504]: def f(s):
...: for l in s.splitlines():
...: yield l + ('X' if l else '')
...:
In [505]: '\n'.join(list(f(s)))
Out[505]: 'some textX\n\nsome other textX'
这是使用列表推导的替代方案 -
In [506]: '\n'.join([x + 'X' if x else '' for x in s.splitlines()])
Out[506]: 'some textX\n\nsome other textX'
作为引用,这就是您使用正则表达式执行此操作的方式 -
Out[507]: re.sub(r'(?<=\S)(?=\n|$)', r'X', s, re.M)
Out[507]: 'some textX\n\nsome other textX'
您需要使用前视和后视。这是表达式的分割 -
(?<= # lookbehind
\S # anything that is not a whitespace character, alt - `[^\n]`
)
(?= # lookahead
\n # newline
| # regex OR
$ # end of line
)
