Parse program parameters

Share your advanced PureBasic knowledge/code with the community.
User avatar
Michael Vogel
Addict
Addict
Posts: 2677
Joined: Thu Feb 09, 2006 11:27 pm
Contact:

Parse program parameters

Post by Michael Vogel »

I need to split program parameters, which may contain single items like 'text"a b c"text'. Here's my approach wich could be certainly improved but works fine for my needs.

Test result for the string 'First_parameter hello"a b c"xxx+"m m" "Parameter 3" fourth':
  • First_parameter
    - First_parameter
    hello"a b c"xxx+"m m"
    - hello
    - a b c
    - xxx+
    - m m
    "Parameter 3"
    - Parameter 3
    fourth
    - fourth

Code: Select all

#Q=#DOUBLEQUOTE$

Procedure CheckParameter(text.s,expression.s,Array result.s(1))

	#Rex=0

	Protected n

	If CreateRegularExpression(#Rex,expression)
		If ExamineRegularExpression(#Rex,text)
			While NextRegularExpressionMatch(#Rex)
				If RegularExpressionMatchLength(#Rex)
					n+1
					ReDim Result(n)
					Result(n)=RegularExpressionMatchString(#Rex)
					;Debug "Match: " + RegularExpressionMatchString(#Rex)
					;Debug "  @"+Str(RegularExpressionMatchPosition(#Rex))+", len "+Str(RegularExpressionMatchLength(#Rex))
				EndIf
			Wend
		EndIf
	EndIf

	ProcedureReturn n

EndProcedure
Procedure.s StripQuotes(s.s)
	
	If PeekA(@s)='"'
		ProcedureReturn StringField(s,2,#Q)
	Else
		ProcedureReturn s
	EndIf
	
EndProcedure

Global Dim p.s(0)
Global Dim s.s(0)

s.s=~"First_parameter hello\"a b c\"xxx+\"m m\" \"Parameter 3\" fourth"
;ReplaceString(s,"'",#Q,#PB_String_InPlace)
Debug s

rp.s=~"([^ \\\"]*(\\\"[^\\\"]*\\\")*)*"
rs.s=~"(?<tick>\\\"?)[^\\\"]*(\\k<tick>)"
Debug "Reg 1: "+rp
Debug "Reg 2: "+rs
Debug ""

z=CheckParameter(s,rp,p())
If z
	For i=1 To z
		Debug p(i)
		o=CheckParameter(p(i),rs,s())
		If o
			For j=1 To o
				Debug " - "+StripQuotes(s(j))
			Next j
		EndIf
	Next i
EndIf