D
D
dollar2018-10-07 01:51:00
JavaScript
dollar, 2018-10-07 01:51:00

How to replace all single characters with some other one?

For example, replace all 1s with 2. But if there are two 1s nearby, then do not replace them.
We try:

'aaa11aaaa1bbb1ccc1d1eeee'.replace(/([^1])1([^1])/g,'$12$2')

Result
"aaa11aaaa2bbb2ccc2d1eeee"

Oops, something went wrong. How to fix regex? The file is very large, not like in the example.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Alekseev, 2018-10-07
@dollar

Something like that:

'aaa11aaaa1bbb1ccc1d1eeee'.replace(/(\D|^)([1]{1})((?=[a-zA-Z]|$))/g, '$12$3')

V
vreitech, 2018-10-07
@fzfx

what went wrong is that c1d1eeeeafter replacing c1d with c2d , you still have 1eeee, which does not fall under the regular season, from the sequence.
try

'aaa11aaaa1bbb1ccc1d1eeee'.replace(/([^1])1{1}/g,'$12')
.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question