How to rename duplicated fields in the text?

Get help with using AutoHotkey (v1.1 and older) and its commands and hotkeys
m3user
Posts: 235
Joined: 17 Jan 2014, 18:11

How to rename duplicated fields in the text?

Post by m3user » 28 Jan 2024, 17:31

Hi, I have strings which contain several fields which may be duplicated. What would be the best approach to rename all duplicated fields? For example, the second and a third etc. occurrence of <field name> field would be replaced with <field name DUP#> etc. Is there a RegEx command to do this?

Example:

Code: Select all

Original string:
text<field name>text<field address>text<field name>text<field address>text<field name>
Expected result:
text<field name>text<field address>text<field name DUP1>text<field address DUP1>text<field name DUP2>
User avatar
andymbody
Posts: 996
Joined: 02 Jul 2017, 23:47

Re: How to rename duplicated fields in the text?

Post by andymbody » 28 Jan 2024, 19:47

Try this

Code: Select all

#Requires AutoHotkey v1.1.35+
#SingleInstance Force

str := "text<field name>text<field address>text<field name>text<field address>text<field name>"
while (p := RegExMatch(str, "(<([^>]+)>)(?=.*?\1)", m)) {
	c := o := 0
	Loop {
		str := RegExReplace(str, m1, "<" m2 " DUP" ++c ">",o,1, p+StrLen(m1))
	} Until o=0
}
MsgBox % "[" str "]"
Last edited by andymbody on 28 Jan 2024, 23:03, edited 2 times in total.
m3user
Posts: 235
Joined: 17 Jan 2014, 18:11

Re: How to rename duplicated fields in the text?

Post by m3user » 29 Jan 2024, 10:40

Thank you, it works great!
andymbody wrote:
28 Jan 2024, 19:47
Try this

Code: Select all

#Requires AutoHotkey v1.1.35+
#SingleInstance Force

str := "text<field name>text<field address>text<field name>text<field address>text<field name>"
while (p := RegExMatch(str, "(<([^>]+)>)(?=.*?\1)", m)) {
	c := o := 0
	Loop {
		str := RegExReplace(str, m1, "<" m2 " DUP" ++c ">",o,1, p+StrLen(m1))
	} Until o=0
}
MsgBox % "[" str "]"
Post Reply

Return to “Ask for Help (v1)”