need help : word replacement
-
Hello,
I want to make a modification in a document that contains several lines of information, and search for example a word named ‘car’ .
If the word ‘car’ is repeated 4 times or more, make the following modification:
replace the word ‘car’ by another word like ‘vehicle’.
If the word ‘car’ is repeated less than 3 times, no change will be made!
Thanks for your help !
-
@Patrick48215712 said in need help : word replacement:
If the word ‘car’ is repeated 4 times or more, make the following modification:
Now that is a very interesting problem. I believe I have a regex (regular expression) that might suit. It needs to be run twice. The first time it annotates the file so that on the second run it makes the changes, and finally removes the annotation.
Using the Replace function:
Find What:(?s).*?\K(\bcar\b)(?=.+@@@)|@@@|(?=.*?\bcar\b.*?\bcar\b.*?\bcar\b.*?\bcar\b).+\K(\z)
Replace With:(?1vehicle)(?2@@@)
Search mode must be regular expression.Obviously you would change the
car
andvehicle
with your choice of words.So in a nutshell the 3rd alternation confirms at least 4 car words exist and annotates the file with
@@@
at the end. Note I have used\b
which is boundary so that carpet is not the word. The first alternation then goes through the file changing ALL occurrences of car with the new word. The second alternation finally removes the@@@
since no more ‘car’ words need changing.As it uses the
\K
it MUST be run with the “Replace All” button ONLY, and TWICE!See if that solves your problem. please do come back and let us know the result.
Terry
-
@Terry-R said in need help : word replacement:
Find What:(?s).?\K(\bcar\b)(?=.+@@@)|@@@|(?=.?\bcar\b.?\bcar\b.?\bcar\b.*?\bcar\b).+\K(\z)
This can be shortened a bit to:
(?s).*?\K(\bcar\b)(?=.+@@@)|@@@|(?=(?:.*?\bcar\b){4}).+\K(\z)
That way you only need to change the word in 2 locations in the first field, instead of 5 times.
Terry
-
Thank you very much Terry R ! Yes! It works perfectly and thanks again for your support :)
-
@Terry-R said in need help : word replacement:
That way you only need to change the word in 2 locations in the first field, instead of 5 times.
Well, if changing it in multiple locations is a problem, maybe even eliminate having to do it twice! :-)
(?s).*?\K(\bcar\b)(?=.+@@@)|@@@|(?=(?:.*?(?1)){4}).+\K(\z)
But yes, this is a nice solution – the original one.
In these types of solution, I often think of future readers that might come along with a similar need.
Perhaps there is benefit in some explanation of how this one actually works is in order.