How to keep identical substrings in vim regex

Ideally, I would like to answer vim:

I want to change

[*, 1, *, *] to [*, 2, *, *]

Here, the stars refer to individual characters in the substring, which I would like to leave unchanged. for instance

[0, 1, 0, 1] to [0, 2, 0, 1]
[1, 1, 1, 1] to [1, 2, 1, 1]

If people know how to do this in perl or python or something else, that would be equally good. Greetings

+3
source share
5 answers

It works:)

1,$s/\[\(\d\+\),\s\+\d\+,\s\+\(\d\+\),\s\+\(\d\+\)\]/[\1, 2, \2, \3]/g

or

%s/\[\(\d\+\),\s\+\d\+,\s\+\(\d\+\),\s\+\(\d\+\)\]/[\1, 2, \2, \3]/
+4
source

The following should do what you want:

:%s/\(\[[^,]*, *\)\(\d\)\([^]]*\]\)/\=submatch(1) . (submatch(2)+1) . submatch(3)/

In vim, that is.

+2
source

Python

>>> a = "[0, 1, 0, 1]"
>>> b = a[:4] + '2' + a[5:]
>>> b
'[0, 2, 0, 1]'

:

>>> c = [0, 1, 0, 1]
>>> c[1] = 2
>>> c
[0, 2, 0, 1]
>>>
+1

.

:%s/\(\[[^,],\s*\)1,/\12,/

, , . , , .

+1

, / , . , , ( perl), .

, $ ,

 my $two=2;  
 $line =~ s/(,\s+)\d+/\1$two/;

, , . . . , , , 2. , [0, 1, 0, 1] [0, 2, 0, 1]
[1, 1, 1, 1] [1, 2, 1, 1]

+1
source

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


All Articles