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:
 
Cookies are required to use this site. You must accept them to continue using the site. Learn more…