Clipping a string?

Get help with using AutoHotkey (v1.1 and older) and its commands and hotkeys
PepeLapiu
Posts: 324
Joined: 19 Jun 2020, 14:06

Clipping a string?

Post by PepeLapiu » 08 Jun 2023, 12:24

So RegEx and strings are the parts I struggle the most with.
Say String := "This is the original string to clip example."

I want to look for the first occurrence of "to" and clip the string to have the "to" and everything after removed. So the result would be Trimmed_string := "This is the original string "

How do I do that?

User avatar
mikeyww
Posts: 26600
Joined: 09 Sep 2014, 18:38

Re: Clipping a string?

Post by mikeyww » 08 Jun 2023, 14:17

Code: Select all

#Requires AutoHotkey v1.1.33
str := "This is the original string to clip to example."
MsgBox % clip(str, "to")

clip(str, fromWord) {
 Return (f := InStr(str, fromWord)) ? SubStr(str, 1, f - 1) : str
}
Oops, changed at the same time as Rowhedder! Looks like the same thing.

RegEx could be

Code: Select all

Return RegExReplace(str, fromWord ".*")
Last edited by mikeyww on 08 Jun 2023, 14:24, edited 3 times in total.

Rohwedder
Posts: 7551
Joined: 04 Jun 2014, 08:33
Location: Germany

Re: Clipping a string?

Post by Rohwedder » 08 Jun 2023, 14:20

Hallo,
try:

Code: Select all

String := "This is the original string to clip example."
IF To := InStr(String, "to")
	String := SubStr(String, 1, To-1)
MsgBox,% "String:`n" String

PepeLapiu
Posts: 324
Joined: 19 Jun 2020, 14:06

Re: Clipping a string?

Post by PepeLapiu » 08 Jun 2023, 17:45

Thanx guys. This has been EXTREMELY helpful.

User avatar
kunkel321
Posts: 975
Joined: 30 Nov 2015, 21:19

Re: Clipping a string?

Post by kunkel321 » 10 Jun 2023, 10:55

Another similar solution:

Code: Select all

String := "This is the original string to clip example."
Delimiter := " to "
TrimmedString := StrSplit(String, Delimiter)
TrimmedString := TrimmedString[1]
MsgBox, TrimmedString is: %TrimmedString% 
ste(phen|ve) kunkel

PepeLapiu
Posts: 324
Joined: 19 Jun 2020, 14:06

Re: Clipping a string?

Post by PepeLapiu » 10 Jun 2023, 19:59

kunkel321 wrote:
10 Jun 2023, 10:55
Another similar solution:

Code: Select all

String := "This is the original string to clip example."
Delimiter := " to "
TrimmedString := StrSplit(String, Delimiter)
TrimmedString := TrimmedString[1]
MsgBox, TrimmedString is: %TrimmedString% 
I guess there is more than one way to skin a cat....interesting!

Post Reply

Return to “Ask for Help (v1)”