Using one swap operation, replace all leading tabs with spaces

In my text, I want to replace all leading tabs with two spaces, but leave the tabs without a leading.

For instance:

a
\tb
\t\tc
\td\te
f\t\tg

( "a\n\tb\n\t\tc\n\td\te\nf\t\tg")

should turn into:

a
  b
    c
  d\te
f\t\tg

( "a\n b\n c\n d\te\nf\t\tg")

In my case, I could do this with a few replace operations, repeating as many times as the maximum level of nesting or until nothing changes.

But is it also impossible to do in one pass?

I tried, but could not come up with something, the best I came up with was a search:

re.sub(r'(^|(?<=\t))\t', '  ', a, flags=re.MULTILINE)

Which "only" makes the wrong replacement (second tab between fand g).

, , (, , ), "count" regex, , ( [cs.se]).

Python, .

+4
3

re.sub , :

import re
s = "a\n\tb\n\t\tc\n\td\te\nf\t\tg";
print(re.sub(r"^\t+", lambda m: "  "*len(m.group()), s, flags=re.M))

Python

+8

, replace() :

>>> s = "a\n\tb\n\t\tc\n\td\te\nf\t\tg"
>>> "\n".join(x.replace("\t","  ",len(x)-len(x.lstrip("\t"))) for x in s.split("\n"))
'a\n  b\n    c\n  d\te\nf\t\tg'
+1

It looks crazy, but it works:

"\n".join([ re.sub(r"^(\t+)"," "*(2*len(re.sub(r"^(\t+).*","\1",x))),x) for x in "a\n\tb\n\t\tc\n\td\te\nf\t\tg".splitlines() ])
+1
source

Source: https://habr.com/ru/post/1651785/


All Articles