B4J Code Snippet Tiny Regex tip

If you use Regex.Split(",",someString) the usual way is
B4X:
Dim s() As String = Regex.Split(",",someString)

Which is fine if you want all the items, but let's assume you only want the third item
you would use
B4X:
Log("Third Item : " & s(2))

You can shortcut all the above code into
B4X:
Log("Third Item : " & Regex.Split(",",someString)(2))
or
B4X:
Dim s As String = Regex.Split(",",someString)(2)
 

sorex

Expert
Licensed User
Longtime User
a common shortcut in a lot of languages indeed but keep in mind that when using a full char split ("") the counter starts from 1 and not 0 in some situations.
(on Android for example)
 

stevel05

Expert
Licensed User
Longtime User
One danger to be aware of using it like this is that if there are not enough elements in the string you are splitting you will get an array index out of bounds error, as you can't check the resulting length before trying to access it.
 

ilan

Expert
Licensed User
Longtime User
One danger to be aware of using it like this is that if there are not enough elements in the string you are splitting you will get an array index out of bounds error, as you can't check the resulting length before trying to access it.

B4X:
    Dim someString = "one,two,three" As String
    Dim s As String = Regex.Split(",",someString)(Regex.Split(",",someString).Length-1)
    Log(s)

i didnot knew you can use the regex.split as an array when it is splitting :)
thanx @Daestrum
 

Swissmade

Well-Known Member
Licensed User
Longtime User
Nice TIP
I have seen that Split can not handle "|" and "?" maybe even more any idea.
 

derez

Expert
Licensed User
Longtime User
Special characters need an escape ("\") before them to work in regex:
there are 12 characters with special meanings: the backslash \, the caret ^, the dollar sign $, the period or dot ., the vertical bar or pipe symbol |, the question mark?, the asterisk or star *, the plus sign +, the opening parenthesis (, the closing parenthesis ), and the opening square bracket [, the opening curly brace {, These special characters are often called "metacharacters".
 
Top