例如,如果我有:
"+----+----+---+---+--+"
是否可以从第二到第四+
替换为-
?
如果我有
"+----+----+---+---+--+"
我想拥有
"+-----------------+--+"
我必须从2-nd替换为4-1的+
到-
。是否可以通过Regex实现这一目标?以及如何?
如果您可以假设第一个字符始终是 +
:
string = '+' + re.sub(r'+', r'-', string[1:], count=3)
lop删除字符串的第一个字符和sub()
前三个+
字符,然后添加初始+
。
如果您不能假定第一个+
是字符串的第一个字符,请首先找到它:
prefix = string.index('+') + 1
string = string[:prefix] + re.sub(r'+', r'-', string[prefix:], count=3)
我宁愿在字符串上迭代,然后根据我发现的东西替换质疑。
secondIndex = 0
fourthIndex = 0
count = 0
for i, c in enumerate(string):
if c == '+':
count += 1
if count == 2 and secondIndex == 0:
secondIndex = i
elif count == 4 and fourthIndex == 0:
fourthIndex = i
string = string[:secondIndex] + '-'*(fourthIndex-secondIndex+1) + string[fourthIndex+1:]
测试:
+----+----+---+---+--+
+-----------------+--+
i使用字符将字符串拆分为字符串,使用该字符替换为分离器。
然后使用所需的分离器在各节中重新加入数组。
example_str="+----+----+---+---+--+"
swap_char="+"
repl_char='-'
ith_match=2
jth_match=4
list_of_strings = example_str.split(swap_char)
new_string = ( swap_char.join(list_of_strings[0:ith_match]) + repl_char +
repl_char.join(list_of_strings[ith_match:jth_match]) +
swap_char + swap_char.join(list_of_strings[jth_match:]) )
print (example_str)
print (new_string)
运行它给出:
$ python ./python_example.py
+----+----+---+---+--+
+-------------+---+--+
带有 REGEX ?是的,这是可能的。
^(+-+){1}((?:+[^+]+){3})
说明:
^
(+-+){1} # read + and some -'s until 2nd +
( # group 2 start
(?:+[^+]+){3} # read +, followed by non-plus'es, in total 3 times
) # group 2 end
测试:
$ cat test.py
import re
pattern = r"^(+-+){1}((?:+[^+]+){3})"
tests = ["+----+----+---+---+--+"]
for test in tests:
m = re.search(pattern, test)
if m:
print (test[0:m.start(2)] +
"-" * (m.end(2) - m.start(2)) +
test[m.end(2):])
调整很简单:
^(+-+){1}((?:+[^+]+){3})
^ ^
- " 1"表示您正在阅读第二' '
- " 3"表示您正在阅读到第四' '
- 这是您需要进行的仅有的2个更改,组号保持不变。
运行:
$ python test.py
+-----------------+--+
这是Pythonic。
import re
s = "+----+----+---+---+--+"
idx = [ i.start() for i in re.finditer('+', s) ][1:-2]
''.join([ j if i not in idx else '-' for i,j in enumerate(s) ])
但是,如果您的字符串是恒定的,并且需要简单
print (s)
print ('+' + re.sub('+---', '----', s)[1:])
输出:
+----+----+---+---+--+
+-----------------+--+
仅使用理解列表:
s1="+----+----+---+---+--+"
indexes = [i for i,x in enumerate(s1) if x=='+'][1:4]
s2 = ''.join([e if i not in indexes else '-' for i,e in enumerate(s1)])
print(s2)
+-----------------+--+
我看到您已经找到了一个解决方案,但是我不太喜欢Regex,所以也许这会有所帮助!: - )