How to replace with variable length characters?

A place to try and solve your RegEx problems.
Post Reply
Julian Shen
Posts: 4
Joined: Fri Oct 31, 2014 3:42 am

How to replace with variable length characters?

Post by Julian Shen »

Ex: replace o to 0 in context.

I have some original context like this:

1o, 2o, 3oo, 5oo, 2ooo, 35oo, 2ooooo-43oooo, Book, look, other, etc.

It's numeric 0 has been set to o in context, so I need to restore character o to 0 after numeric character 1-9, but I can not replace all o to 0 directly because it have another none numeric character o in other word.

I can find target by search condition ([0-9]+)(o+), but I can't replace it because I can put $1 in replace parameter header, but the $2 is a variable length o character. I don't know how to replace this variable length o to variable length 0.

Repeating execute replace regex ([0-9]+)o{1} is unacceptable because I must put it in batch replace. How should I set this regex replace string in this case?
silentguy
Posts: 6
Joined: Fri Dec 12, 2014 10:21 am

Re: How to replace with variable length characters?

Post by silentguy »

The easiest solution I can think of is this:
Replace

Code: Select all

(?<=\do*)o
with

Code: Select all

0
This uses the fact that you can ask what's in front of a place without having to match it. Therefore this matches all "o"s that have a digit followed by any amount of "o"s. Due to the fact that this \do+ is not actually part of the match it finds all the o's at once...

Ah, I miss playing around with regular expressions :)
Julian Shen
Posts: 4
Joined: Fri Oct 31, 2014 3:42 am

Re: How to replace with variable length characters?

Post by Julian Shen »

Oh, it's work! Thank you.

So, this is put the variable length condition in pattern parameter parts of (?<=) , just a nested sub-condition. I thought this parameter of pattern must be a fix value before.

Thank you very much for your help.

Julian.
Post Reply