如何使用 2 个分隔符的正则表达式拆分字符串,但将分隔符保留在 Python 中?
How to split a string with a regex of 2 delimiters, but keep the delimiters in Python?
假设我有这个字符串。 "+2x-10+5"
。我想把它分成 ['+2x','-10','+5']
.
所以,我可以使用正则表达式使它成为['2x','10','5']
,但我想保留分隔符,即加号和减号。
我该怎么做?
不要使用 re.split()
,使用 re.findall()
和匹配每个子表达式的正则表达式。
import re
s = "+2x-10+5"
result = re.findall(r'[-+]\w+', s)
print(result)
假设我有这个字符串。 "+2x-10+5"
。我想把它分成 ['+2x','-10','+5']
.
所以,我可以使用正则表达式使它成为['2x','10','5']
,但我想保留分隔符,即加号和减号。
我该怎么做?
不要使用 re.split()
,使用 re.findall()
和匹配每个子表达式的正则表达式。
import re
s = "+2x-10+5"
result = re.findall(r'[-+]\w+', s)
print(result)