B4J Code Snippet Tiny Regex tip

If you use Regex.Split(",",someString) the usual way is
Code:
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
Code:
Log("Third Item : " & s(2))

You can shortcut all the above code into
Code:
Log("Third Item : " & Regex.Split(",",someString)(2))
or
Code:
Dim s As String = Regex.Split(",",someString)(2)
 
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)
 
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.
 
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.

Code:
    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
 
Nice TIP
I have seen that Split can not handle "|" and "?" maybe even more any idea.
 
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".
 
Back
Top