Page 1 of 1

Get multiple fields at end of line

Posted: 21 Feb 2021, 13:38
by roysubs
I read a line in from a file to which I then split up into an array

Code: Select all

GetTag(tag) {
    FileRead, pwd, %PwdFile%
    Loop, read, %PwdFile%
    {
        line = %A_LoopReadLine%
        arrx := StrSplit(line, " ")
        l1 := % arrx.1
        l2 := % arrx.2
        l3 := % arrx.3
        l4 := % arrx.4
I am happy with l1, l2, l3 like this as they have specific meanings, but I would like to populate l4 with "everything after l3" as that part can be a free form string with many spaces in it. How could I do this? Do you think building the string "%l1% %l2% %l3%", and then split the line on that string so that I get the latter part of the string would be efficient or are there better ways?
Also, am I using the *wrong kind* of array here? There is a more modern way of doing arrays I think? (Autohotkey often has the "old way" and "new way" of doing things of course!).

Re: Get multiple fields at end of line

Posted: 21 Feb 2021, 15:40
by Spawnova
I would just loop everything from 4 to array length into a new variable

Code: Select all

str := "something somethingelse moresomething lots of spaces after the somethings"
s := strsplit(str," ")

rest := ""
loop % s.length()-3
	rest .= (a_index > 1 ? " " : "") s[3+a_index]

msgbox % s[1] "`n" s[2] "`n" s[3] "`n" rest

Re: Get multiple fields at end of line

Posted: 21 Feb 2021, 16:32
by TLM
roysubs wrote:
21 Feb 2021, 13:38
...I would like to populate l4 with "everything after l3" as that part can be a free form string with many spaces in it. How could I do this?
Based off of your specific question and to keep it simple, you could use a conditional statement like this:

Code: Select all

	l1 := arrx.1 ; you don't need the %'s here
	l2 := arrx.2
	l3 := arrx.3
	if ( a_index = 4 )
	{
		l4 := arrx.4
	}
There's no "new way", it's really personal preference.

Re: Get multiple fields at end of line

Posted: 21 Feb 2021, 16:48
by mikeyww

Code: Select all

arr := StrSplit(SubStr(str, 1, (pos := RegExMatch(str, "(.*? ){3}\K.+", rest)) ? pos - 2 : StrLen(str)), " ")
arr.Push(rest)

Re: Get multiple fields at end of line

Posted: 21 Feb 2021, 23:20
by roysubs
These are all really great and really cool techniques. Thanks.

Re: Get multiple fields at end of line

Posted: 22 Feb 2021, 03:29
by just me
Array := StrSplit(String [, Delimiters, OmitChars, MaxParts])

Re: Get multiple fields at end of line

Posted: 22 Feb 2021, 06:42
by mikeyww
Thank you, @just me-- useful reminder!