(PB) String Between Characters

Posted by on April 26, 2011

This is a small purebasic function used to retrieve a string between two known characters, it also allows you to provide a starting position.

Procedure.s str_between_char( *Source.CHARACTER, First.C, Last.C, StartAt.i = 0 )
	Define.i dwLength
	
	*Source + (StartAt * SizeOf(CHARACTER))
	Repeat
		If *Source\c = First ; If this character matches the First character
			*Source + SizeOf(CHARACTER)
			dwLength = *Source
			Repeat ; Repeat until we find an occurrance with the Last character
				*Source + SizeOf(CHARACTER)
			Until *Source\c = Last
			dwLength = (*Source - dwLength)
			ProcedureReturn PeekS( *Source - dwLength, dwLength ) ; Peek the output string
			Break
		EndIf
		*Source + SizeOf(CHARACTER)
	Until *Source\c = #Null
	
EndProcedure

Example use:

Define.s str 		= "dd(hallo)xyz(a)"
Define.s result 	= str_between_char(@str, '(', ')', 2)
Debug result

If you’re working on a parser or similar project this will sure come in handy.
Enjoy!

0 Comments on (PB) String Between Characters

Closed