Search and replace with regex after some manipulation.

Get help with using AutoHotkey (v1.1 and older) and its commands and hotkeys
Nixcalo
Posts: 116
Joined: 06 Feb 2018, 04:24

Search and replace with regex after some manipulation.

15 Sep 2023, 08:58

Hi everyone!

I am fighting with the RegexReplace and RegexMatch functions as they are not very intuitive.

It happens that I need to convert units to metric in a string. For example, the string Source is:
Source:="It has a range of 1,274 miles and it cruises at 270 miles per hour"

And I want it to replace it to Target:="It has a range of 2050 kilometers and it cruises at 474 kilometers per hour"
Of course, the specific numbers and positions may vary.

I have no problem with the issue of decimal/thousand delimiters, it's a matter of tweaking the code, but I AM having problems with the search and replace code itself.
I started with something like:
if Source contains miles {
FoundPos := RegExMatch(Target, "(\d+,?\d*) kilómetros", OutputVar)
...
}

But then I realized I have no idea how to search for 1,274 miles (I believe the haystack could be "(\d+,?\d*) miles" and the needle "$1 kilometers", and then multiply the resulting matching pattern by 1.609 and round it and then paste the result in the source string in the right place and save it as target.

While I more or less manage with RegexReplace, RegexMatch is much more complicated for me to use, because it only returns a position! What am I supposed to do with knowing that 1,274 kilometers is in the 18th position of the string???

Thank you for any help.

I have to check if we have something like miles and miles per hour in the same string, as they convert differently, but I think that will not be problematic... perhaps extending the haystack or something.
Rohwedder
Posts: 7655
Joined: 04 Jun 2014, 08:33
Location: Germany

Re: Search and replace with regex after some manipulation.

15 Sep 2023, 10:36

Hallo,
try:

Code: Select all

Source:="It has a range of 1,274 miles and it cruises at 270 miles per hour"
Pos := 1, Target := Source
While, Pos := RegExMatch(Source, "([\d,]+)\s+miles", N, Pos)
{
	Pos += StrLen(N)
	Target := StrReplace(Target, N, Round(RegExReplace(N, "\D")*1.609344) " kilometers")
}
MsgBox,% Target
or with decimal points taken into account:

Code: Select all

Source:="It has a range of 1,273.9 miles and it cruises at 270 miles per hour"
Pos := 1, Target := Source
While, Pos := RegExMatch(Source, "([\d,.]+)\s+miles", N, Pos)
{
	Pos += StrLen(N)
	Target := StrReplace(Target, N, Round(RegExReplace(N, "[^\d.]")*1.609344) " kilometers")
}
MsgBox,% Target

Return to “Ask for Help (v1)”

Who is online

Users browsing this forum: Bing [Bot], fiendhunter and 97 guests