regex question

Get help with using AutoHotkey (v1.1 and older) and its commands and hotkeys
obob
Posts: 9
Joined: 01 Jul 2021, 04:41

regex question

Post by obob » 27 Sep 2021, 03:09

I've been looking for a while and I need help with following regex problem
I want to pass strings in this format to the script:

Code: Select all

cmd_someCommand_par_someParameter
How would you use regex (or perhaps a less CPU taxing method?)
to break the string into variables?

Code: Select all

cmd = someCommand
par = someParameter
User avatar
mikeyww
Posts: 26883
Joined: 09 Sep 2014, 18:38

Re: regex question

Post by mikeyww » 27 Sep 2021, 05:28

Code: Select all

part := StrSplit(A_Args.1, "_"), cmd := part.2, par := part.4
MsgBox, 64, Parts, cmd = %cmd%`n`npar  = %par%
Or:

Code: Select all

part := StrSplit(A_Args.1, "_"), v1 := part.1, %v1% := part.2, v2 := part.3, %v2% := part.4
MsgBox, 64, Parts, % v1 " = " %v1% "`n`n" v2 "  = " %v2%
User avatar
boiler
Posts: 16925
Joined: 21 Dec 2014, 02:44

Re: regex question

Post by boiler » 27 Sep 2021, 06:04

Or using RegEx:

Code: Select all

RegExMatch(A_Args.1, "^cmd_([^_]*)_par_(.*)", m), cmd := m1, par := m2
MsgBox, % "cmd = " cmd "`npar = " par
obob
Posts: 9
Joined: 01 Jul 2021, 04:41

Re: regex question

Post by obob » 27 Sep 2021, 06:48

Thank you, beautiful people!
obob
Posts: 9
Joined: 01 Jul 2021, 04:41

Re: regex question

Post by obob » 27 Sep 2021, 08:19

boiler wrote:
27 Sep 2021, 06:04
Or using RegEx:

Code: Select all

RegExMatch(A_Args.1, "^cmd_([^_]*)_par_(.*)", m), cmd := m1, par := m2
MsgBox, % "cmd = " cmd "`npar = " par
Thank you, I like this solution because it allows to have _underscore as part of the command and parameter.
However when I parse a string without parameter, it also omits cmd.

The strings I parse are sometimes only commands without parameter.
Do you know how to adjust RegExMatch to allow an optional parameter?
User avatar
boiler
Posts: 16925
Joined: 21 Dec 2014, 02:44

Re: regex question

Post by boiler » 27 Sep 2021, 08:44

You could do this:

Code: Select all

RegExMatch(A_Args.1, "^cmd_([^_]*)(_par_(.*))?", m), cmd := m1, par := m3
obob
Posts: 9
Joined: 01 Jul 2021, 04:41

Re: regex question

Post by obob » 27 Sep 2021, 09:28

thank you. You set me on the right path to solve the problem.
I wanted commands to be able to use underscores in their names,
so I adjusted the convention of how the strings will be written, so it allows multiple underscores

Code: Select all

RegExMatch((A_Args.1, "^cmd_([^,]*)(,\s?par_(.*))?", m), cmd := m1, par := m3
Post Reply

Return to “Ask for Help (v1)”