2 回答
TA贡献1797条经验 获得超4个赞
使用
^([^,]*),|,(?=[^,]*$)
替换为\1||
. 见证明。
解释
--------------------------------------------------------------------------------
^ the beginning of the string
--------------------------------------------------------------------------------
( group and capture to \1:
--------------------------------------------------------------------------------
[^,]* any character except: ',' (0 or more
times (matching the most amount
possible))
--------------------------------------------------------------------------------
) end of \1
--------------------------------------------------------------------------------
, ','
--------------------------------------------------------------------------------
| OR
--------------------------------------------------------------------------------
, ','
--------------------------------------------------------------------------------
(?= look ahead to see if there is:
--------------------------------------------------------------------------------
[^,]* any character except: ',' (0 or more
times (matching the most amount
possible))
--------------------------------------------------------------------------------
$ before an optional \n, and the end of
the string
--------------------------------------------------------------------------------
) end of look-ahead
import re
regex = r'^([^,]*),|,(?=[^,]*$)'
test_str = r'101, "Name1", "Designation1", "blah1", "Blah1", 20200914001'
subst = r'\1||'
print(re.sub(regex, subst, test_str))
结果:101|| "Name1", "Designation1", "blah1", "Blah1"|| 20200914001.
TA贡献1906条经验 获得超10个赞
您可以拆分第一个(maxsplit=1从左起)和最后一个(maxsplit=1从右起)逗号并连接结果,例如:
>>> line = '101, "Name1", "Designation1", "blah1", "Blah1", 20200914001'
>>> first, rest = line.split(',', maxsplit=1)
>>> rest, last = rest.rsplit(',', maxsplit=1)
>>> '||'.join((first, rest, last))
'101|| "Name1", "Designation1", "blah1", "Blah1"|| 20200914001'
添加回答
举报